$nin - Amazon DocumentDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$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命令的代码示例,请选择要使用的语言的选项卡:

Node.js
const { MongoClient } = require('mongodb'); async function findBooksNotInCategories(categories) { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); const books = await db.collection('books').find({ category: { $nin: categories } }).toArray(); console.log(books); client.close(); } findBooksNotInCategories(['Fiction', 'Mystery']);
Python
from pymongo import MongoClient def find_books_not_in_categories(categories): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] books = list(db.books.find({ 'category': { '$nin': categories } })) print(books) client.close() find_books_not_in_categories(['Fiction', 'Mystery'])