Question 1:
Find the total number of item quantity (use TotalQty as alias) for customers having customerName as "abc" and "xyz". Sort the result in descending order of "TotalQty".
Output Format:
Each output document of the above query should look like the sample given below:
{"_id":"abc","TotalQty":9}
{"_id":"xyz", "TotalQty":99}
CodePudding user response:
Making the assumption that your documents contains a TotalQty
field, and also some other additional fields that you want to strip out:
[
{
"_id": "Aaron",
"fieldB": "ABC",
"TotalQty": 99
},
{
"_id": "Charles",
"fieldB": "ABC",
"TotalQty": 9
},
{
"_id": "Brian",
"fieldB": "Another",
"TotalQty": 999
}
]
Running a query like this:
db.collection.aggregate([
{
$sort: {
"TotalQty": -1
}
},
{
$project: {
_id: 1,
TotalQty: 1
}
}
])
To give you results like this:
[
{
"TotalQty": 999,
"_id": "Brian"
},
{
"TotalQty": 99,
"_id": "Aaron"
},
{
"TotalQty": 9,
"_id": "Charles"
}
]
Info:
You haven't mentioned in your question about summing a list of products, but you could do it like this: Need to sum from array object value in mongodb
Example code:
CodePudding user response:
I hope this is what you're expecting?