I am making a query in MongoDB in which I need to obtain the most sold product, for now I have managed to obtain the list of products and order it by the amount of sales but I only need to return the product with the most sales, this is my query:
db.sales.aggregate(
[
{
$unwind : "$detail"
},
{
$project : {
"name" : "$detail.name"
}
},
{
$group: {
_id: "$name",
quantity: { $sum: 1 }
}
},
{
$sort: {
quantity: -1
}
},
]
);
And this is the answer:
[
{
"_id": "Producto 2",
"quantity": 38
},
{
"_id": "Producto 3",
"quantity": 28
},
{
"_id": "Producto 1",
"quantity": 9
}
]
How can I get only the element with the largest quantity? Thanks.
CodePudding user response:
You're very close, but as @rickhg12hs has already mentioned, you need to add $limit
.
Example playground here: https://mongoplayground.net/p/9bRRgUI4Izo
db.collection.aggregate([
{
$unwind: "$detail"
},
{
$project: {
"name": "$detail.name"
}
},
{
$group: {
_id: "$name",
quantity: {
$sum: 1
}
}
},
{
$sort: {
quantity: -1
}
},
{
$limit: 1
}
])
There are other approaches to this, but this will work for you.