Question

I looked around and couldn't find a good answer for this, and I'm completely new to Mongo so here is the thing if someone can help. I have a collection in mongo which holds user related data, in this manner:

{user: 4, rate: 2, location: 1}
{user: 5, rate: 4, location: 1}
{user: 6, rate: 3, location: 1}
{user: 5, rate: 2, location: 1}
{user: 4, rate: 5, location: 1}
...
{user: x, rate: y, location: z}

Now I need a query that will return me all the users on certain location (here is 1 but can be anything) together with final sum of all the rates for that user, and all that ordered by that same sum of rates (hope this makes sense). So something like this :

{4: 7, 5: 6, 6: 3} -> {user: sum(rate)} - ordered by sum(rate)

Any ideas guys? I will be doing this in mongoengine for Django so if anyone knows how to do this there cool, but if not I'll just do a raw query so any help is good. Thanks a bunch!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top