本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$and
Amazon DocumentDB 中的$and運算子用於合併多個表達式,並將其評估為單一條件。true 如果所有提供的表達式評估為 true,則傳回 ,false否則傳回 。此運算子適用於將多個條件套用至查詢。
參數
範例 (MongoDB Shell)
以下範例示範使用 $and 運算子來尋找「使用者」集合中「年齡」欄位大於 18 且「狀態」欄位為「作用中」的所有文件。
建立範例文件
db.users.insertMany([
{ name: "John", age: 25, status: "active" },
{ name: "Jane", age: 17, status: "active" },
{ name: "Bob", age: 30, status: "inactive" },
{ name: "Alice", age: 22, status: "active" }
]);
查詢範例
db.users.find({
$and: [
{ age: { $gt: 18 } },
{ status: "active" }
]
});
輸出
[
{ "_id" : ObjectId("614e3c4b63f5892e7c4e2345"), "name" : "John", "age" : 25, "status" : "active" },
{ "_id" : ObjectId("614e3c4b63f5892e7c4e2347"), "name" : "Alice", "age" : 22, "status" : "active" }
]
程式碼範例
若要檢視使用 $and命令的程式碼範例,請選擇您要使用的語言標籤:
- Node.js
-
const { MongoClient } = require('mongodb');
async function findActiveUsersOlderThan18() {
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 users = db.collection('users');
const activeUsersOlderThan18 = await users.find({
$and: [
{ age: { $gt: 18 } },
{ status: 'active' }
]
}).toArray();
console.log(activeUsersOlderThan18);
await client.close();
}
findActiveUsersOlderThan18();
- Python
-
from pymongo import MongoClient
def find_active_users_older_than_18():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
users = db['users']
active_users_older_than_18 = list(users.find({
'$and': [
{'age': {'$gt': 18}},
{'status': 'active'}
]
}))
print(active_users_older_than_18)
client.close()
find_active_users_older_than_18()