Database

db={orders:[{"_id":"63f37d1ac3dff5dd6d8cd156","cartItems":[{"qty":1,"product":{"_id":"63515ad7d5f84ecbaac38f1e","code":"1","name":"Coca-Cola","pricePerItem":3,"group":"Milk",},"price":3,"total":3,}],createdAt:ISODate("2023-02-20")},{"_id":"63f37cd9c3dff5dd6d8cd14b","cartItems":[{"qty":1,"product":{"_id":"63515aeed5f84ecbaac38f24","code":"2","name":"Fanta","pricePerItem":4,"group":"Drink",},"price":4,"total":4,},{"qty":2,"product":{"_id":"63515ad7d5f84ecbaac38f1e","code":"1","name":"Coca-Cola","pricePerItem":3,"group":"Milk",},"price":3,"total":6,}],createdAt:ISODate("2023-02-20")}]}

Query

db.orders.aggregate([{$match:{createdAt:{$gte:ISODate("2023-02-19"),$lt:ISODate("2023-02-24")}}},{$set:{popularity:{$sum:"$cartItems.qty"}}},{"$setWindowFields":{"partitionBy":null,"sortBy":{"popularity":-1},"output":{"popularityRank":{$rank:{}}}}},{$sort:{popularityRank:-1}}])

Result