Reputation: 179
I have products like this:
[
{
"_id": 1,
"name": "Apple",
"price": 3,
"stock": 5
},
{
"_id": 2,
"name": "Banana",
"price": 1,
"stock": 6
}
]
How to query and filter the products that have the total price highest? (total price of a product = price * stock)
Thanks for help!
Upvotes: 0
Views: 70
Reputation: 51195
An aggregate query to work with:
$set
- Set totalPrice
field by multiplying both price
and stock
fields.$sort
- Order by totalPrice
descending.$limit
- Take only one document.db.collection.aggregate([
{
$set: {
totalPrice: {
"$multiply": [
"$price",
"$stock"
]
}
}
},
{
$sort: {
totalPrice: -1
}
},
{
$limit: 1
}
])
Note: Although the above query gets the document with the highest total price, it gets the first and only one document.
For the above scenario mentioned that possible there are multiple documents with the highest total price, so we need a ranking.
$set
- Set totalPrice
field by multiplying both price
and stock
fields.$rank
- Rank the documents by sorting with totalPrice
descending.$match
- Filter the documents with rank: 1
.db.collection.aggregate([
{
$set: {
totalPrice: {
"$multiply": [
"$price",
"$stock"
]
}
}
},
{
$setWindowFields: {
sortBy: {
totalPrice: -1
},
output: {
rank: {
$rank: {}
}
}
}
},
{
$match: {
rank: 1
}
}
])
Sample Mongo Playground ($rank
)
Upvotes: 1