本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$nin
该$nin运算符用于匹配不在指定数组中的值。它是$in运算符的倒数,它匹配指定数组中的值。
Planner 版本 2.0 添加了对索引的支持$nin。
参数
-
field:要检查的字段。 -
array:要检查的值数组。
字段名称中的美元 ($)
有关在嵌套对象中查询$前缀字段的限制$nin,请参阅字段名称中的美元符号($)和句点(.)。
示例(MongoDB 外壳)
以下示例演示如何使用$nin运算符来查找category字段不等于 “虚构” 或 “神秘” 的文档。
创建示例文档
db.books.insertMany([ { title: "The Great Gatsby", author: "F. Scott Fitzgerald", category: "Fiction" }, { title: "To Kill a Mockingbird", author: "Harper Lee", category: "Fiction" }, { title: "The Girl on the Train", author: "Paula Hawkins", category: "Mystery" }, { title: "The Martian", author: "Andy Weir", category: "Science Fiction" }, { title: "The Alchemist", author: "Paulo Coelho", category: "Philosophy" } ])
查询示例
db.books.find({ category: { $nin: ["Fiction", "Mystery"] } })
输出
[
{
_id: ObjectId('...'),
title: 'The Martian',
author: 'Andy Weir',
category: 'Science Fiction'
},
{
_id: ObjectId('...'),
title: 'The Alchemist',
author: 'Paulo Coelho',
category: 'Philosophy'
}
]
代码示例
要查看使用该$nin命令的代码示例,请选择要使用的语言的选项卡: