Group Mongo documents by id and get the latest document by timestamp

前端 未结 3 1513
孤独总比滥情好
孤独总比滥情好 2021-01-13 09:44

Imagine we have the following set of documents stored in mongodb:

{ \"fooId\" : \"1\", \"status\" : \"A\", \"timestamp\" : ISODate(\"2016-01-01T00:00:00.000Z         


        
3条回答
  •  萌比男神i
    2021-01-13 10:03

    If you are doing and aggregation, you need to do similar to SQL , which mean specify the aggregation operation per column, the only option you have is use the $$ROOT operator

    db.test.aggregate(
       [
        { $sort: { timestamp: 1 } },
         {
           $group:
             {
               _id: "$fooId",
               timestamp: { $last: "$$ROOT" }
             }
         }
       ]
    );
    

    But that will change the output a little bit

    { "_id" : "1", "timestamp" : { "_id" : ObjectId("570e6be3e81c8b195818e7fa"), 
      "fooId" : "1", "status" : "A", "timestamp" :ISODate("2016-01-01T00:00:00Z"), 
      "otherInfo" : "BAR" } }
    

    If you want to return the original document format, you probably need a $project stage after that

提交回复
热议问题