MongoDB - Query on the last element of an array?

后端 未结 9 1116
醉梦人生
醉梦人生 2020-11-29 06:51

I know that MongoDB supports the syntax find{array.0.field:\"value\"}, but I specifically want to do this for the last element in the array, which means I don\'

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 07:44

    Version 3.6 use aggregation to achieve the same.

    db.getCollection('deviceTrackerHistory').aggregate([
       {
         $match:{clientId:"12"}
       },
       {
         $project:
          {
             deviceId:1,
             recent: { $arrayElemAt: [ "$history", -1 ] }
          }
       }
    ])
    

提交回复
热议问题