D
D
Dmitry2210602018-03-25 21:31:33
MongoDB
Dmitry221060, 2018-03-25 21:31:33

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
    }
}]

You need to sort the results 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)
How can I achieve this (I would like to see a detailed answer, I recently started deal with the database)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry221060, 2018-03-27
@Dmitry221060

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 question

Ask a Question

731 491 924 answers to any question