1

I am executing query in Mongo shell and require the output of this query to execute the second query. The first query is the aggregate query to find the average.

The first query is :

db.table_name.aggregate([{$group: {_id:{userId:'$userId'},avgRating:{$avg:"$rating"}}}])

Now using the _id (userId) in the output, I wanna fetch the data from user table.

2
  • 1
    May we see your queries, edited into the question, and formatted nicely? I have trimmed out material from your question that is not directly relevant, and please do note that requesting urgency is not well-received here. Commented Sep 27, 2016 at 7:40
  • Do you want to query two different table simultaneously? Commented Sep 27, 2016 at 8:11

1 Answer 1

2

No need for another query, you can still run the same aggregate operation but this time adding another pipeline that uses the $lookup operator which pipes the results from the previous $group pipeline to do a left join on the user collection:

db.table_name.aggregate([
    {
        "$group": {
            "_id": "$userId",
            "avgRating": { "$avg": "$rating" }
        }
    },
    {
        "$lookup": {
            "from": "user",
            "localField": "_id",
            "foreignField": "_id",
            "as": "users"
        }
    }
])

If your MongoDB version does not support the $lookup operator, then you will need two queries, run as follows:

var cursor = db.table_name.aggregate([
    {
        "$group": {
            "_id": "$userId",
            "avgRating": { "$avg": "$rating" }
        }
    }
]);

var results = cursor.map(function(doc){ 
    var user = db.users.findOne({ "_id": doc._id })
    return {
        user: user,
        avgRating: doc.avgRating
    }; 
});
printjson(results);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.