Mrj
Mrj

Reputation: 69

How to aggregate documents with `$in` in mongodb?

There are my documents :

> db.messages.find({})

 {   "_id" : ObjectId("5c1f9e3d37e9e12650b9971a"), 
"groupId" : ObjectId("5c0fe59f5dcbbe30b732616c"), 
"content" : "hi"
}
{   "_id" : ObjectId("5c1f9e3d37e9e12650b9971a"), 
    "groupId" : ObjectId("5c0fe59f5dcbbe30b732616c"), 
   "content" : "hello"
}
{   "_id" : ObjectId("5c1f9e3d37e9e12650b9971a"), 
"groupId" : ObjectId("5c0fe59f5dcbbe30b732616d"), 
"content" : "hi"
}
 {   "_id" : ObjectId("5c1f9e3d37e9e12650b9971a"), 
  "groupId" : ObjectId("5c0fe59f5dcbbe30b732616e"), 
  "content" : "hi"
}

one group has many messages . now I has groupIds like: [ObjectId("5c0fe59f5dcbbe30b732616c"),ObjectId("5c0fe59f5dcbbe30b732616d")]

I want to find the latest one message using $in with sql like :

SELECT * FROM `message` WHERE `groupId` IN (xx,xx) group by 
groupId order by id desc .

how to do it with mongo shell ?

Upvotes: 0

Views: 57

Answers (1)

Ashh
Ashh

Reputation: 46441

You have to first $sort with the createdAt field to get the latest message in the $group stage using the $first aggregation

db.collection.aggregate([
  { "$match": { "groupId": { "$in": [ObjectId("5c0fe59f5dcbbe30b732616c"), ObjectId("5c0fe59f5dcbbe30b732616d")] }}},
  { "$sort": { "createdAt": -1 }},
  { "$group": {
    "_id": "$groupId",
    "content": { "$first": "$content" }
  }}
])

Upvotes: 1

Related Questions