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

前端 未结 3 1515
孤独总比滥情好
孤独总比滥情好 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条回答
  •  日久生厌
    2021-01-13 09:52

    Though there is no direct way to bring back original documents and I don't see any value, but try following aggregation query:

    db.collection.aggregate([
       {$sort: {fooId:1, timestamp: -1}},
       {$group:{_id:"$fooId", doc:{$first:"$$ROOT"}}},
       {$project:{_id:0, doc:["$doc"]}}
    ]).forEach(function(item){
    
      printjson(item.doc[0]);
    
    });
    

    This query will emit:

    { 
        "_id" : ObjectId("570e76d5e94e6584078f02c4"), 
        "fooId" : "2", 
        "status" : "B", 
        "timestamp" : ISODate("2016-01-02T00:00:00.000+0000"), 
        "otherInfo" : "BAR"
    }
    { 
        "_id" : ObjectId("570e76d5e94e6584078f02c8"), 
        "fooId" : "3", 
        "status" : "D", 
        "timestamp" : ISODate("2016-01-04T00:00:00.000+0000"), 
        "otherInfo" : "BAR"
    }
    { 
        "_id" : ObjectId("570e76d5e94e6584078f02c2"), 
        "fooId" : "1", 
        "status" : "C", 
        "timestamp" : ISODate("2016-01-03T00:00:00.000+0000"), 
        "otherInfo" : "BAR"
    }
    

提交回复
热议问题