0

I'm doing the course of MongoDB and I'm on the first exercise of week 5. The first exercise consists on getting the author who has more comments.

The first thing I did was check how looks the data and after that I started writing the query and that's what I got:

db.posts.aggregatae([
    { $unwind: "$comments" },
    { $group: 
        { 
            _id: "$author", 
            num_posts:{ $sum:1 }
        }
    },
    { $sort: 
        { "num_posts": -1 } 
    }
]);

The query works and counts the num of comments correctly but when I try to sort the results it didn't work. I tried to change the $group stage to this:

    { $group: 
        { _id: "$author" },
        num_posts:{ $sum:1 }
    }

But I get the error:

Error: command failed: {
     "errmsg" : "exception": A pipeline state specification object must contain exactly 
     one field.", "code" : 16435, "ok" : 0

1 Answer 1

1

The problem with your query is you are grouping by a non-existing key, you need to group by the comments' author key to get the author (from the embedded comments subdocuments array) with the most number of comments as follows:

db.posts.aggregate([
    { "$unwind": "$comments"},
    {
        "$group": {
            "_id": "$comments.author", 
            "num_posts": { "$sum": 1 }
        }
    },
    { 
        "$sort": { "num_posts": -1 }
    },
    { "$limit": 1 }
]);
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.