John
John

Reputation: 2761

Get last inserts of the disctinct property type list in mongodb

I have a collection of Account. Each Account document has 3 properties _id, type, age; and there are 3 distinct types Male,Female & Other. Any single document will bear only one of the types.

{
_id:ObjectId(xxxxx1),
type:"Male",
age:20

}
{
_id:ObjectId(xxxxx2),
type:"Female",
age:20

}
{
_id:ObjectId(xxxxx3),
type:"Male",
age:21

}
{
_id:ObjectId(xxxxx4),
type:"Other",
age:30

}
{
_id:ObjectId(xxxxx5),
type:"Female",
age:31

}

My problem is I want to extract very last inserted document of each three type: The result will be 3 documents

{
_id:ObjectId(xxxxx3), <--- last insert of the Male type
type:"Male",
age:21

}
{
_id:ObjectId(xxxxx4), <--- last insert of the Other type
type:"Other",
age:30

}
{
_id:ObjectId(xxxxx5), <--- last insert of the Female type
type:"Female",
age:31

}

How can I design query for this?

Upvotes: 1

Views: 29

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17935

You need to use MongoDB's aggregation :

db.Account.aggregate([
      {$group : {_id : '$type', lastDoc : {$last : '$$ROOT'}}},
      {$replaceRoot : {newRoot : '$lastDoc'}}])

Test : mongoplayground

Explanation :

  1. In aggregate $group stage will group all the matching docs based on condition _id : '$type', So all the docs with same type will be grouped together & using $last we'll get the last document in the grouping process.

  2. Using replaceRoot we'll make lastDoc object as new root of the document.

Upvotes: 1

Related Questions