MongoDB - Query on the last element of an array?

后端 未结 9 1075
醉梦人生
醉梦人生 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 ] }
          }
       }
    ])
    
    0 讨论(0)
  • 2020-11-29 07:45

    Starting Mongo 4.4, the aggregation operator $last can be used to access the last element of an array:


    For instance, within a find query:

    // { "myArray": ["A", "B", "C"] }
    // { "myArray": ["D"] }
    db.collection.find({ $expr: { $eq: [{ $last: "$myArray" }, "C"] } })
    // { "myArray": ["A", "B", "C"] }
    

    Or within an aggregation query:

    db.collection.aggregate([
      { $addFields: { last: { $last: "$myArray" } } },
      { $match: { last: "C" } }
    ])
    
    0 讨论(0)
  • 2020-11-29 07:48

    For the answer use $arrayElemAt,if i want orderNumber:"12345" and the last element's value $gt than "value"? how to make the $expr? thanks!

    For embedded arrays - Use $arrayElemAt expression with dot notation to project last element.

     db.col.find({$expr: {$gt: [{"$arrayElemAt": ["$array.field", -1]}, value]}})
    
    0 讨论(0)
提交回复
热议问题