1π
β
The MongoDB feature you are looking for is the Aggregation Framework.
Here is an example query in the mongo
shell:
db.collection.aggregate(
// Find matching documents (can take advantage of suitable index if present)
{ $match: {
location: 1
}},
// Add up rates by user
{ $group: {
_id: "$user",
rates: { $sum: "$rate" }
}},
// Order by total rates (ascending)
{ $sort: { rates: 1 }}
)
Sample results given your data in the question:
[
{
"_id" : 6,
"rates" : 3
},
{
"_id" : 5,
"rates" : 6
},
{
"_id" : 4,
"rates" : 7
}
]
As an optional step in the aggregation, you might want to use $project
to rename the grouped _id
field to user
.
π€Stennie
Source:stackexchange.com