Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$in
Amazon DocumentDB 中的运算符是一种逻辑查询运算符,它允许您查找字段值等于数组中指定的任何值的文档。$in
参数
字段名称中的美元 ($)
有关在嵌套对象中查询$前缀字段的限制$in,请参阅字段名称中的美元符号($)和句点(.)。
示例(MongoDB 外壳)
以下示例演示如何使用$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()