Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb aggregation framework group + project

I have the following issue:

this query return 1 result which is what I want:

> db.items.aggregate([ {$group: { "_id": "$id", version: { $max: "$version" } } }])

{
"result" : [
    {
        "_id" : "b91e51e9-6317-4030-a9a6-e7f71d0f2161",
        "version" : 1.2000000000000002
    }
],
"ok" : 1
}

this query ( I just added projection so I can later query for the entire document) return multiple results. What am I doing wrong?

> db.items.aggregate([ {$group: { "_id": "$id", version: { $max: "$version" } }, $project: { _id : 1 } }])

  {
"result" : [
    {
        "_id" : ObjectId("5139310a3899d457ee000003")
    },
    {
        "_id" : ObjectId("513931053899d457ee000002")
    },
    {
        "_id" : ObjectId("513930fd3899d457ee000001")
    }
],
"ok" : 1
}
like image 487
SnIcK Avatar asked May 14 '26 09:05

SnIcK


1 Answers

found the answer

1. first I need to get all the _ids

db.items.aggregate( [ 
  { '$match': { 'owner.id': '9e748c81-0f71-4eda-a710-576314ef3fa' } },
  { '$group': { _id: '$item.id', dbid: { $max: "$_id" } } } 
]);

2. then i need to query the documents

db.items.find({ _id: { '$in': "IDs returned from aggregate" } });

which will look like this:

db.items.find({ _id: { '$in': [ '1', '2', '3' ] } });
like image 57
SnIcK Avatar answered May 16 '26 12:05

SnIcK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!