$nor(逻辑查询)

适用对象: MongoDB vCore

$nor 运算符对表达式数组执行逻辑 NOR 运算,并选择所有指定表达式失败的文档。

语法

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

参数

参数 类型 DESCRIPTION
expression 数组 表达式数组,所有这些表达式都必须为 false 才能包含文档

例子

示例 1:基本 NOR作

查找没有超过 15 名全职员工和 20 多名兼职员工的商店:

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

这会生成以下输出:

      {
        eventName: 'Steal the Show Sale',
        promotionalDates: {
          startDate: { Year: 2024, Month: 6, Day: 23 },
          endDate: { Year: 2024, Month: 7, Day: 1 }
        },
        discounts: [
          { categoryName: 'Charms', discountPercentage: 10 },
          { categoryName: 'Bracelets', discountPercentage: 13 }
        ]
      }

示例 2:复杂 NOR作

查找没有任何以下条件的商店:2024 年 9 月的销售额超过 100000、“数字手表”销售额或促销:

db.stores.find({
  $nor: [
    { "sales.totalSales": { $gt: 100000 } },
    { "sales.salesByCategory.categoryName": "Digital Watches" },
    {
      "promotionEvents": {
        $elemMatch: {
          "promotionalDates.startDate.Month": 9,
          "promotionalDates.startDate.Year": 2024
        }
      }
    }
  ]
})

这会生成以下输出:

  {
    _id: 'binary-test',
    name: 'Test Store',
    logo: Binary(Buffer.from("627566666572", "hex"), 0),
    signature: Binary(Buffer.from("74657374", "hex"), 0)
  }

示例 3:具有多个字段条件的 NOR

查找不符合以下任何位置和员工条件的商店:

db.stores.find({
  $nor: [
    { "location.lat": { $gt: 0 } },
    { "staff.totalStaff.fullTime": { $lt: 10 } },
    { "sales.totalSales": { $gt: 50000 } }
  ]
})

这会生成以下输出:

  {
    _id: 'db5051a8-17d1-4b01-aa2f-31e64623e5ac',
    name: 'First Up Consultants | Watch Mart - Port Zack',
    location: { lat: -62.6354, lon: 46.2917 },
    staff: { totalStaff: { fullTime: 12, partTime: 9 } },
    sales: {
      totalSales: 6118,
      salesByCategory: [ { categoryName: 'Digital Watches', totalSales: 6118 } ]
    },
    promotionEvents: [
      {
        eventName: 'Incredible Bargain Blitz',
        promotionalDates: {
          startDate: { Year: 2024, Month: 6, Day: 23 },
          endDate: { Year: 2024, Month: 6, Day: 30 }
        },
        discounts: [
          {
            categoryName: 'Chronograph Watches',
            discountPercentage: 13
          },
          { categoryName: 'Diving Watches', discountPercentage: 21 }
        ]
      },
      {
        eventName: 'Fantastic Deals Festival',
        promotionalDates: {
          startDate: { Year: 2024, Month: 9, Day: 21 },
          endDate: { Year: 2024, Month: 9, Day: 29 }
        },
        discounts: [
          { categoryName: 'Digital Watches', discountPercentage: 25 },
          { categoryName: 'Pilot Watches', discountPercentage: 17 }
        ]
      }
    ]
  }