适用对象:
MongoDB vCore
当所有表达式的计算结果为$and
时,运算符true
返回 true
。 它在表达式数组上执行逻辑 AND作。 如果任何表达式的计算结果 false
为,则整个 $and
表达式返回 false
。 此运算符可用于组合必须全部满足的多个条件。
语法
$and
运算符的语法如下:
{
$and: [ <expression1>, <expression2>, ... ]
}
参数
DESCRIPTION | |
---|---|
<expression1>, <expression2>, ... |
要计算的两个或多个表达式。 所有表达式的计算结果true 必须为要返回$and 的作true 。 |
示例:
示例 1:查找销售额高且员工充足的商店
该示例查找总销售额超过 100,000 和 30 多名员工总数的商店。
db.stores.aggregate([
{
$project: {
name: 1,
totalSales: "$sales.totalSales",
totalStaff: {
$add: ["$staff.employeeCount.fullTime", "$staff.employeeCount.partTime"]
},
meetsHighPerformanceCriteria: {
$and: [
{ $gt: ["$sales.totalSales", 100000] },
{ $gt: [{ $add: ["$staff.employeeCount.fullTime", "$staff.employeeCount.partTime"] }, 30] }
]
}
}
},
{ $limit: 2 }
])
该查询返回满足高销售额和人员配备条件的商店。
{
"_id": "905d1939-e03a-413e-a9c4-221f74055aac",
"name": "Trey Research | Home Office Depot - Lake Freeda",
"totalStaff": 31,
"meetsHighPerformanceCriteria": false
},
{
"_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6",
"name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort",
"totalStaff": 27,
"meetsHighPerformanceCriteria": false
}
示例 2:验证促销事件日期
该示例检查促销事件是否同时具有有效的开始日期和结束日期(所有日期组件均为正数)。
db.stores.aggregate([
{ $match: {"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74"} },
{
$project: {
name: 1,
promotionEvents: {
$map: {
input: "$promotionEvents",
as: "event",
in: {
eventName: "$$event.eventName",
hasValidDates: {
$and: [
{ $gt: ["$$event.promotionalDates.startDate.Year", 0] },
{ $gt: ["$$event.promotionalDates.startDate.Month", 0] },
{ $gt: ["$$event.promotionalDates.startDate.Day", 0] },
{ $gt: ["$$event.promotionalDates.endDate.Year", 0] },
{ $gt: ["$$event.promotionalDates.endDate.Month", 0] },
{ $gt: ["$$event.promotionalDates.endDate.Day", 0] }
]
}
}
}
}
}
}
])
该查询验证所有日期组件是否都是开始日期和结束日期的正数。
{
"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74",
"name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury",
"promotionEvents": [
{ "eventName": "Massive Markdown Mania", "hasValidDates": true },
{ "eventName": "Fantastic Deal Days", "hasValidDates": true },
{ "eventName": "Discount Delight Days", "hasValidDates": true },
{ "eventName": "Super Sale Spectacular", "hasValidDates": true },
{ "eventName": "Grand Deal Days", "hasValidDates": true },
{ "eventName": "Major Bargain Bash", "hasValidDates": true }
]
}