Answer the question
In order to leave comments, you need to log in
How to sort records by sum of nested object values?
There is a collection containing the user ID and command usage statistics -
[{
"userID": 0,
"stat": {
"command1": 5,
"command4": 1
}
},{
"userID": 1,
"stat": {
"command2": 8,
"command1": 1
}
},{
"userID": 2,
"stat": {
"command6": 1,
"command3": 2,
"command5": 1
}
}]
myCollection.find({})
by the total number of commands used (i.e. user "1" will be in the first place, "0" in the second, and "2" in the third) Answer the question
In order to leave comments, you need to log in
Okay, I did it myself.
myCollection.aggregate([
{'$project': {
"stat": 1,
"userID": 1,
"statParsed": {"$objectToArray": "$stat"}
}},
{"$unwind": "$statParsed"},
{"$group": {
"_id": {
"userID": "$userID",
"stat": "$stat"
},
"sum": {"$sum": "$statParsed.v"}
}}
]).sort({"sum": -1}).toArray((err, data) => {
...
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question