本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$and
$and 彙總運算子會評估多個表達式,並true僅在所有表達式評估為 時傳回 true。如果任何表達式為 false,則會傳回 false。
參數
範例 (MongoDB Shell)
下列範例示範如何使用 $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()