简体   繁体   中英

How can we find the recent record from each group in mongodb?

I want to find out most recent record from each group. My collection:-

{ "_id" : ObjectId("1"), "loginID" : Ram.1234@gmail.com , "name" : Ram, "date" : ISODate("2017-02-01T00:00:00Z"),Site:blog.com,opertion:modified }
{ "_id" : ObjectId("2"), "loginID" : Arjun34@gmail.com, "name" : Arjun, "date" : ISODate("2017-02-01T00:00:00Z").site:ketanblog.com,opertion:updated }
{ "_id" : ObjectId("3"), "loginID" :Ram.1234@gmail.com , "name" : Ram, "date" : ISODate("2017-02-03T00:00:00Z"),Site:blogtec.com,opertion:modified }
{ "_id" : ObjectId("4"), "loginID" : Arjun34@gmail.com, "name" : Arjun, "date" : ISODate("2017-02-08T00:00:00Z"),Site:blogpec.com,opertion:updated }
{ "_id" : ObjectId("5"), "loginID" : Arjun34@gmail.com, "name" : Arjun, "date" : ISODate("2017-02-07T00:00:00Z") ,Site:blog.com,opertion:read}
{ "_id" : ObjectId("6"), "loginID" : shyam78@gmail.com, "name" : Shyam, "date" : ISODate("2017-02-09T00:00:00Z"),site:ketanblog.com,opertion:deleted }
{ "_id" : ObjectId("7"), "loginID" : shyam78@gmail.com, "name" : Shyam, "date" : ISODate("2017-02-03T00:00:00Z") ,site:ketanblog.com,opertion:updated}
{ "_id" : ObjectId("8"), "loginID" : Arjun34@gmail.com, "name" : Arjun, "date" : ISODate("2017-02-03T00:00:00Z"),Site:blogtrt.com,opertion:read  }

My Expected output:-

{ "_id" : ObjectId("3"), "loginID" : Ram.1234@gmail.com, "name" : Ram, "date" : ISODate("2017-02-03T00:00:00Z"),Site:blogtec.com,opertion:modified  }
{ "_id" : ObjectId("4"), "loginID" : Arjun34@gmail.com, "name" : Arjun, "date" : ISODate("2017-02-08T00:00:00Z"),Site:blogpec.com,opertion:updated  }
{ "_id" : ObjectId("6"), "loginID" : shyam78@gmail.com, "name" : Shyam, "date" : ISODate("2017-02-09T00:00:00Z"),Site:ketanblog.com,opertion:deleted  }
  1. Sort by date to keep the latest data for each group at the top
  2. Group by login id, get the first record for each group which is latest. It discards other records in each group
db.coll.aggregate([
{
  $sort : {"$date": - 1}
}, 
{
 $group: {
   _id : "$loginID", 
  data : { 
    $first : "$$ROOT" 
  } 
 } 
}
])

You can try,

  • $sort by date descending order
  • $group by loginID and add first recent document in recent
  • $replaceRoot to replace recent into new root
  • $sort new grouped documents
db.collection.aggregate([
  { $sort: { date: -1 } },
  {
    $group: {
      _id: "$loginID",
      recent: { $first: "$$ROOT" }
    }
  },
  { $replaceRoot: { newRoot: "$recent" } },
  { $sort: { date: -1 } }
])

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM