MongoDB 查找所有数组元素都等于某个值的文档 [英] MongoDB find Documents where all array elements equal some value

查看:84
本文介绍了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.

这篇关于MongoDB 查找所有数组元素都等于某个值的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆