$and(逻辑查询)

适用对象: MongoDB vCore

$and 运算符对表达式数组执行逻辑 AND 运算,并选择满足所有表达式的文档。

语法

{ $and: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }

参数

参数 类型 说明
expression 数组 结果中包含文档必须全部为 true 的表达式数组

例子

示例 1:基本 AND作

查找拥有 10 多名全职员工和 15 多名兼职员工的商店:

db.stores.find({
  $and: [
    { "staff.totalStaff.fullTime": { $gt: 10 } },
    { "staff.totalStaff.partTime": { $gt: 15 } }
  ]
})

示例 2:复杂 AND作

查找总销售额超过 100000 家且其销售类别中同时具有“游戏控制器”和“家庭影院投影仪”的商店:

db.stores.find({
  $and: [
    { "sales.totalSales": { $gt: 100000 } },
    { "sales.salesByCategory.categoryName": "Game Controllers" },
    { "sales.salesByCategory.categoryName": "Home Theater Projectors" }
  ]
})

示例 3:组合多个条件

查找在 2024 年 6 月和 2024 年 9 月举办促销活动的商店,折扣超过 20%:

db.stores.find({
  $and: [
    {
      "promotionEvents": {
        $elemMatch: {
          "promotionalDates.startDate.Month": 6,
          "promotionalDates.startDate.Year": 2024
        }
      }
    },
    {
      "promotionEvents": {
        $elemMatch: {
          "promotionalDates.startDate.Month": 9,
          "promotionalDates.startDate.Year": 2024,
          "discounts.discountPercentage": { $gt: 20 }
        }
      }
    }
  ]
})