MongoDB 查找所有数组元素都等于某个值的文档
集合:
db.test.find()
{
{ "_id" : ObjectId(...), "arr" : [ "Today", "is", null ] }
{ "_id" : ObjectId(...), "arr" : [ null, null, null ] }
}
我试图找到所有 arr
等于某个值的所有文档.在这个例子中,当给定 null
时,我想要包含 arr : [null, null, null]
的文档.
I'm trying to find all documents where all of arr
equals some value. In this example, I would want the document containing arr : [null, null, null]
when given null
.
这个解决方案接近我想要的;但是,我的数组数据没有 $elemMatch
引用的键.有没有一种方法可以在不增加不必要的成本或重组我的数据的情况下完成此查询?
This solution is close to what I want; however, my array data do not have keys for an $elemMatch
to reference. Is there a way to accomplish this query without being unnecessarily costly or restructuring my data?
谢谢!
您可以使用 $elemMatch
查询运算符.它只需要一个查询.
You can use $elemMatch
query operator. It just needs a query.
db.test.find( { arr: { $not: { $elemMatch: { $ne: null } } } } )
"$elemMatch" + "$ne"
这部分包括arr
数组至少没有一个空值的所有文档.
This part includes all the documents where arr
array don't have at least one null value.
这些是至少有一个非空值的所有文档.
These are all the documents which has at least one not null value.
$not
这部分会保留所有不在"$elemMatch" + "$ne"
中的文件.
This part will keep the all the documents which are not in "$elemMatch" + "$ne"
.
这些是所有值为 null
的文档.
These are all the documents that has its all of values as null
.
请适应不存在字段的边缘情况,以确保事情按预期进行.
Please accommodate edge cases where field doesn't exist to make sure things work as expected.