user1460015
user1460015

Reputation: 2003

Trying to extract the $first document from collection

After piping various documents through the aggregate framework I finally have the resultant documents.

The problem now is that I only want the $first and $last document.

The final document looks like this (huge list):

            ...
            {
                    "_id" : "Kaila Deibler",
                    "count" : 406
            },
            {
                    "_id" : "Jessika Dagenais",
                    "count" : 406
            },
            {
                    "_id" : "Tamika Schildgen",
                    "count" : 404
            },
            ...

The mongo shell command that I used to produce the document is:
db.talks.aggregate([{$project: {_id: 0, comments: "$comments"}}, {$unwind: "$comments"}, {$group: {_id: "$comments.author", count: {$sum: 1}}}, {$sort: {count: -1}}])

But I only need the first and last document so I attempted something like this:
db.talks.aggregate([{$project: {_id: 0, comments: "$comments"}}, {$unwind: "$comments"}, {$group: {_id: "$comments.author", count: {$sum: 1}}}, {$sort: {count: -1}}, {$first: "$_id"}])

I tried other implementations but can't seem to figure out when/where to implement $first and $last

Any suggestions?

Upvotes: 0

Views: 226

Answers (2)

user1460015
user1460015

Reputation: 2003

Here is my own answer to this question:

db.talks.aggregate([{$project: {_id: 0, comments: "$comments"}}, {$unwind: "$comments"}, {$group: {_id: "$comments.author", count: {$sum: 1}}}, {$sort: {count: -1}}, {$group: {_id: "$_id.comments.author", first: {$first: "$_id"}, last: {$last: "_id"}}}])

Since I want to pull the first and last document after the sort I have to apply another $group with $first and $last. The result:

{
        "result" : [
                {
                        "_id" : null,
                        "first" : "Elizabet Kleine",
                        "last" : "Mariela Sherer"
                }
        ],
        "ok" : 1
}

Note the "_id" : null. Is this necessary?
If anyone has a better solution please share.

Upvotes: 0

Andre de Frere
Andre de Frere

Reputation: 2743

$first and $last are aggregation functions in the $group pipeline, which means you need to use them inside the $group document.

db.talks.aggregate([{$project: {_id: 0, comments: "$comments"}}, {$unwind: "$comments"}, {$group: {_id: "$comments.author", count: {$sum: 1}, first: {$first:"$_id"}}}, {$sort: {count: -1}}])

Similarly for $last

You can find an example that shows this here

Upvotes: 1

Related Questions