MongoDB - Query on the last element of an array?

后端 未结 9 1126
醉梦人生
醉梦人生 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:43

    In 3.2 this is possible. First project so that myField contains only the last element, and then match on myField.

    db.collection.aggregate([
       { $project: { id: 1, myField: { $slice: [ "$myField", -1 ] } } },
       { $match: { myField: "myValue" } }
    ]);
    

提交回复
热议问题