MongoDB - Query on the last element of an array?

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

    You can use $expr ( 3.6 mongo version operator ) to use aggregation functions in regular query.

    Compare query operators vs aggregation comparison operators.

    For scalar arrays

    db.col.find({$expr: {$gt: [{$arrayElemAt: ["$array", -1]}, value]}})
    

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

    db.col.find({$expr: {$gt: [{"$arrayElemAt": ["$array.field", -1]}, value]}})
    

    Spring @Query code

    @Query("{$expr:{$gt:[{$arrayElemAt:[\"$array\", -1]}, ?0]}}")
    ReturnType MethodName(ArgType arg);
    

提交回复
热议问题