Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$and
Amazon DocumentDB 中的$and运算符用于组合多个表达式并将其作为单个条件进行评估。true如果所有提供的表达式的计算结果均为,则返回true,false否则返回。此运算符对于将多个条件应用于查询很有用。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$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()