MongoDB - 查询数组的最后一个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28680295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:18:57  来源:igfitidea点击:

MongoDB - Query on the last element of an array?

arraysmongodbmongoosemongodb-queryspring-data-mongodb

提问by Joseph Blair

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't know the index. Is there some kind of operator for this, or am I out of luck?

我知道 MongoDB 支持语法find{array.0.field:"value"},但我特别想对数组中的最后一个元素执行此操作,这意味着我不知道索引。是否有某种运算符,或者我不走运?

EDIT: To clarify, I want find() to only return documents where a field in the last element of an array matches a specific value.

编辑:为了澄清,我希望 find() 仅返回数组最后一个元素中的字段与特定值匹配的文档。

采纳答案by Joseph Blair

I posted on the official Mongo Google group here, and got an answer from their staff. It appears that what I'm looking for isn't possible. I'm going to just use a different schema approach.

我在此处的官方 Mongo Google 群组上发帖,并从他们的工作人员那里得到了答复。看来我要找的东西是不可能的。我将只使用不同的模式方法。

回答by jdeyrup

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

在 3.2 中这是可能的。第一个项目使 myField 只包含最后一个元素,然后在 myField 上进行匹配。

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

回答by Sagar Veeram

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

您可以使用$expr( 3.6 mongo version operator ) 在常规查询中使用聚合函数。

Compare query operatorsvs aggregation comparison operators.

比较query operatorsvs aggregation comparison operators

For scalar arrays

对于标量数组

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

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

对于嵌入式数组 - 使用$arrayElemAt带点符号的表达式来投影最后一个元素。

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

Spring @Querycode

弹簧@Query代码

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

回答by Kaushal

use $slice.

使用$slice

db.collection.find( {}, { array_field: { $slice: -1 } } )

Editing: You can make use of { <field>: { $elemMatch: { <query1>, <query2>, ... } } }to find a match.

编辑:您可以使用 { <field>: { $elemMatch: { <query1>, <query2>, ... } } }来查找匹配项。

But it won't give exactly what you are looking for. I don't think that is possible in mongoDB yet.

但它不会给出你正在寻找的东西。我认为这在 mongoDB 中是不可能的。

回答by Ramil Muratov

Not sure about performance, but this works well for me:

不确定性能,但这对我很有效:

db.getCollection('test').find(
  {
    $where: "this.someArray[this.someArray.length - 1] === 'pattern'"
  }
)

回答by KARTHIKEYAN.A

Version 3.6use aggregation to achieve the same.

3.6 版使用聚合来实现相同的功能。

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

回答by Ricky

You could use $position: 0whenever you $push, and then always query array.0to get the most recently added element. Of course then, you wont be able to get the new "last" element.

你可以使用$position: 0,只要你$push,然后总是查询array.0以获得最近添加的元素。当然,您将无法获得新的“最后”元素。

回答by Xavier Guihot

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

从 开始Mongo 4.4,聚合运算符$last可用于访问数组的最后一个元素:



For instance, within a findquery:

例如,在find查询中:

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


Or within an aggregationquery:

或在aggregation查询中:

db.collection.aggregate([
  { $addFields: { last: { $last: "$myArray" } } },
  { $match: { last: "C" } }
])

回答by Robin Jiao

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!

对于答案使用$arrayElemAt,如果我想要 orderNumber:"12345" 和最后一个元素的值 $gt 而不是 "value"?如何制作$expr?谢谢!

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

对于嵌入式数组 - 使用$arrayElemAt带点符号的表达式来投影最后一个元素。

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