查找数组不包含MongoDB中具有特定字段值的文档的文档 [英] Find documents with arrays not containing a document with a particular field value in MongoDB

查看:1379
本文介绍了查找数组不包含MongoDB中具有特定字段值的文档的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找不包含至少一个具有特定字段值的文档的所有文档.例如,这是一个示例集合:

I'm trying to find all documents that do not contain at least one document with a specific field value. For example here is a sample collection:

{  _id : 1,
  docs : [
        { foo : 1,
          bar : 2},
        { foo : 3,
          bar : 3}
         ]
},
{  _id : 2,
  docs : [
        { foo : 2,
          bar : 2},
        { foo : 3,
          bar : 3}
         ]
}

我想找到docs块中没有一个文档不包含至少一个foo = 1记录的记录,在上面的示例中,应该只返回第二个文档.

I want to find every record where there is not a document in the docs block that does not contain at least one record with foo = 1. In the example above, only the second document should be returned.

我尝试了以下操作,但是它只会告诉我是否有不匹配的内容(返回文档1.

I have tried the following, but it only tells me if there are any that don't match (which returns document 1.

db.collection.find({"docs": { $not: {$elemMatch: {foo: 1 } } } })

更新:上面的查询确实有效.很多时候,我的数据是错误的,而不是我的代码.

UPDATE: The query above actually does work. As many times happens, my data was wrong, not my code.

我还查看了 $ nin运算符,但是示例仅在数组包含以下内容时显示原始值列表,而不是附加文档.当我尝试使用类似以下内容的方法进行操作时,它将查找EXACT文档,而不仅仅是我想要的foo字段.

I have also looked at the $nin operator but the examples only show when the array contains a list of primitive values, not an additional document. When I've tried to do this with something like the following, it looks for the EXACT document rather than just the foo field I want.

db.collection.find({"docs": { $nin: {'foo':1 } } })

反正有基本操作员来完成此操作吗?

Is there anyway to accomplish this with the basic operators?

推荐答案

使用

Using $nin will work, but you have the syntax wrong. It should be:

db.collection.find({'docs.foo': {$nin: [1]}})

这篇关于查找数组不包含MongoDB中具有特定字段值的文档的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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