MongoDb, query the last, and group by

后端 未结 2 1303
执笔经年
执笔经年 2021-01-15 14:07

I m actually having trouble when dealing with MongoDb.

I need to :

  • get all of the last entries
  • concerning a field
  • like : SELECT MAX(i
2条回答
  •  难免孤独
    2021-01-15 14:40

    $last gives you the value of the last document which is processed by your grouping. You can not predict the order in which documents are processed, unless you sort the documents. So you don't get the results you expect.

    Try adding a $sort stage before your $group stage to get the documents in ascending date order:

    db.collection.aggregate(
       [
         { $sort: {
               "control_date":1
           }
         },
         {
           $group:
             {
               _id: "$zone._id",
               lastRegistered: { $last: "$_id" },
               zoneName:"$zone.zoneName",
               control_id:"$_id",
               actif:"$actif",
             }
         }
       ]
    )
    

提交回复
热议问题