本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$nin
$nin 運算子用於比對不在指定陣列中的值。這是$in運算子的反向,其符合指定陣列中的值。
規劃器 2.0 版已新增 的索引支援。 $nin
參數
-
field:要檢查的欄位。 -
array:要檢查的值陣列。
欄位名稱中的美元 ($)
欄位名稱中的 Dollar($) 和 dot(.) 如需在巢狀物件$nin中查詢字$首欄位的限制,請參閱 。
範例 (MongoDB Shell)
下列範例示範如何使用 $nin運算子來尋找category欄位不等於 "Fiction" 或 "Mystery" 的文件。
建立範例文件
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命令的程式碼範例,請選擇您要使用的語言標籤: