本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$in
$in聚合运算符检查数组中是否存在指定值。true如果在数组中找到该值,则返回,false否则返回。
参数
-
value:要搜索的值。
-
array: 要在其中搜索的数组。
示例(MongoDB 外壳)
以下示例演示如何使用$in操作员来检查每位员工的技能组合中是否存在特定技能。
创建示例文档
db.employees.insertMany([
{ _id: 1, name: "Sarah", skills: ["Python", "JavaScript", "SQL"] },
{ _id: 2, name: "Mike", skills: ["Java", "C++", "Go"] },
{ _id: 3, name: "Emma", skills: ["Python", "Ruby", "Rust"] }
]);
查询示例
db.employees.aggregate([
{
$project: {
name: 1,
hasPython: { $in: ["Python", "$skills"] }
}
}
]);
输出
[
{ _id: 1, name: 'Sarah', hasPython: true },
{ _id: 2, name: 'Mike', hasPython: false },
{ _id: 3, name: 'Emma', hasPython: true }
]
代码示例
要查看使用$in聚合运算符的代码示例,请选择要使用的语言的选项卡:
- Node.js
-
const { MongoClient } = require('mongodb');
async function example() {
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('employees');
const result = await collection.aggregate([
{
$project: {
name: 1,
hasPython: { $in: ["Python", "$skills"] }
}
}
]).toArray();
console.log(result);
await client.close();
}
example();
- Python
-
from pymongo import MongoClient
def example():
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['employees']
result = list(collection.aggregate([
{
'$project': {
'name': 1,
'hasPython': { '$in': ['Python', '$skills'] }
}
}
]))
print(result)
client.close()
example()