本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$and
$and聚合运算符计算多个表达式,并且true仅当所有表达式的计算结果均为true时才返回。如果有任何表达式false,则返回false。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$and运算符来检查产品是否满足多个标准。
创建示例文档
db.products.insertMany([
{ _id: 1, name: "Laptop", price: 1200, inStock: true },
{ _id: 2, name: "Mouse", price: 25, inStock: false },
{ _id: 3, name: "Keyboard", price: 75, inStock: true }
]);
查询示例
db.products.aggregate([
{
$project: {
name: 1,
price: 1,
inStock: 1,
affordable: {
$and: [
{ $lt: ["$price", 100] },
{ $eq: ["$inStock", true] }
]
}
}
}
]);
输出
[
{ _id: 1, name: 'Laptop', price: 1200, inStock: true, affordable: false },
{ _id: 2, name: 'Mouse', price: 25, inStock: false, affordable: false },
{ _id: 3, name: 'Keyboard', price: 75, inStock: true, affordable: true }
]
代码示例
要查看使用$and聚合运算符的代码示例,请选择要使用的语言的选项卡:
- 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('products');
const result = await collection.aggregate([
{
$project: {
name: 1,
price: 1,
inStock: 1,
affordable: {
$and: [
{ $lt: ["$price", 100] },
{ $eq: ["$inStock", true] }
]
}
}
}
]).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['products']
result = list(collection.aggregate([
{
'$project': {
'name': 1,
'price': 1,
'inStock': 1,
'affordable': {
'$and': [
{ '$lt': ['$price', 100] },
{ '$eq': ['$inStock', True] }
]
}
}
}
]))
print(result)
client.close()
example()