I have the below collection in mongodb
{
"_id": {
"$oid": "632998b73211535e81cebadb"
},
"locationName": "",
"orderId": "541961903613",
"transactionId": "Sep1520221228",
"customerId": "1663240552828",
"locationId": "WALMRTLOC09",
"storeType": "AS",
"tenantId": "1517911f-f507-426e-8764-536129741eab",
"orderTotal": 157.92,
"isActive":true,
"items": [
{
"_id": {
"$oid": "63231101ad8b7d798778b77e"
},
"item_id": "milk123",
"title": "Sara Milk",
"quantity": 24,
"msrp": 7.59,
"offerPrice": 6.58
}
],
"tenantName": "walmart",
"createdAt": {
"$date": {
"$numberLong": "1663670455252"
}
},
"updatedAt": {
"$date": {
"$numberLong": "1663670455252"
}
}
}
I have tried the below aggregation
const data = await TransactionModel.aggregate([
{
$match: {
$and:[
{createdAt: {
$gte: new Date(req.body.filter.startDate),
$lte: new Date(req.body.filter.endDate)
}
},
{orderTotal:{"$gte":0}}
]
}
},
{
$group: {
_id: null,
totalCount: {
$sum: 1
},
activeCount: {
$sum: {
$cond: [
{
$eq: ['$isActive', true]
},
1,
0
]
}
}
}
},
{
$project: {
_id: 0,
totalCount: 1,
activeCount: 1,
inactiveCount: {
$subtract: ['$totalCount', '$activeCount']
}
}
}
]);
I will have multiple data in a collection for a unique transactionId. I need to aggregate the entire collection and get the data for the top 10 sold products based on the items which is a object array. Where the output for the top 10 product will be
[ {title: "milk", totalPrice: 30}, {title: "cookies", totalPrice: 40}, {title: "tea", value: 20}]
What will be the aggregate function for this?