abaracedo
abaracedo

Reputation: 1454

MongoDB using $sort on aggregation not sorting

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

Upvotes: 0

Views: 984

Answers (1)

chridam
chridam

Reputation: 103455

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

Upvotes: 1

Related Questions