本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$in
Amazon DocumentDB 中的$in運算子是一種邏輯查詢運算子,可讓您尋找欄位值等於陣列中指定任何值的文件。
參數
欄位名稱中的美元 ($)
欄位名稱中的 Dollar($) 和 dot(.) 如需在巢狀物件$in中查詢字$首欄位的限制,請參閱 。
範例 (MongoDB Shell)
下列範例示範如何使用 $in運算子來尋找 color 欄位為所提供陣列中其中一個值的文件。
建立範例文件
db.colors.insertMany([
{ "_id": 1, "color": "red" },
{ "_id": 2, "color": "green" },
{ "_id": 3, "color": "blue" },
{ "_id": 4, "color": "yellow" },
{ "_id": 5, "color": "purple" }
])
查詢範例
db.colors.find({ "color": { "$in": ["red", "blue", "purple"] } })
輸出
{ "_id": 1, "color": "red" },
{ "_id": 3, "color": "blue" },
{ "_id": 5, "color": "purple" }
程式碼範例
若要檢視使用 $in命令的程式碼範例,請選擇您要使用的語言標籤:
- Node.js
-
const { MongoClient } = require('mongodb');
async function findByIn() {
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 collection = db.collection('colors');
const result = await collection.find({ "color": { "$in": ["red", "blue", "purple"] } }).toArray();
console.log(result);
await client.close();
}
findByIn();
- Python
-
from pymongo import MongoClient
def find_by_in():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client.test
collection = db.colors
result = list(collection.find({ "color": { "$in": ["red", "blue", "purple"] } }))
print(result)
client.close()
find_by_in()