database 如何在 Mongo 中进行“NOT IN”查询?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6391643/
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 08:14:09  来源:igfitidea点击:

How do I do a "NOT IN" query in Mongo?

mongodbdatabase

提问by TIMEX

This is my document:

这是我的文档:

{ 
    title:"Happy thanksgiving",
    body: "come over for dinner",
    blocked:[
       {user:333, name:'john'},
       {user:994, name:'jessica'},
       {user:11, name: 'matt'},
    ]
}

What is the query to find all documents that do not have user 11 in "blocked"?

查找“已阻止”中没有用户 11 的所有文档的查询是什么?

回答by Justin Jenkins

You can use $inor $ninfor "not in"

您可以使用$in$nin表示“不在”

Example ...

例子 ...

> db.people.find({ crowd : { $nin: ["cool"] }});

I put a bunch more examples here: http://learnmongo.com/posts/being-part-of-the-in-crowd/

我在这里放了更多例子:http: //learnmongo.com/posts/being-part-of-the-in-crowd/

回答by Zugwalt

Since you are comparing against a single value, your example actually doesn't need a NOT IN operation. This is because Mongo will apply its search criteria to every element of an array subdocument. You can use the NOT EQUALS operator, $ne, to get what you want as it takes the value that cannot turn up in the search:

由于您正在与单个值进行比较,因此您的示例实际上不需要 NOT IN 操作。这是因为 Mongo 将其搜索条件应用于数组子文档的每个元素。您可以使用 NOT EQUALS 运算符 $ne 来获取您想要的内容,因为它采用了无法在搜索中出现的值:

db.myCollection.find({'blocked.user': {$ne: 11}});

However if you have many things that it cannot equal, that is when you would use the NOT IN operator, which is $nin. It takes an array of values that cannot turn up in the search:

但是,如果您有许多不能相等的东西,那么您将使用 NOT IN 运算符,即 $nin。它需要一组无法在搜索中出现的值:

db.myCollection.find({'blocked.user': {$nin: [11, 12, 13]}});

回答by kane

Try the following:

请尝试以下操作:

db.stack.find({"blocked.user":{$nin:[11]}})

This worked for me.

这对我有用。

回答by Femi

See http://docs.mongodb.org/manual/reference/operator/query/nin/#op._S_nin

请参阅http://docs.mongodb.org/manual/reference/operator/query/nin/#op._S_nin

db.inventory.find( { qty: { $nin: [ 5, 15 ] } } )

This query will select all documents in the inventory collection where the qty field value does not equal 5 nor 15. The selected documents will include those documents that do not contain the qty field.

If the field holds an array, then the $nin operator selects the documents whose field holds an array with no element equal to a value in the specified array (e.g. , , etc.).

此查询将选择库存集合中 qty 字段值不等于 5 或​​ 15 的所有文档。选定的文档将包括那些不包含 qty 字段的文档。

如果该字段包含一个数组,则 $nin 运算符选择其字段包含一个数组的文档,该数组的元素不等于指定数组中的值(例如 、 等)。