Mongodb 在 $and 中使用多个 $or 查询

Mongodb query with multiple $or inside $and

我想要的记录如果类型为 0 或 2,则状态不应等于 0,如果类型 = 3,则忽略状态。

我试过这种方法,但没有用。

db.activities.find({
    $and: [
        {
            $or: [
                { type: { $in: [0, 2] } },
                { status: { $ne: 0 } },
            ],
        },
        {
            $or: [{ type: { $eq: 3 } }],
        },
    ]
})
    .projection({})
    .sort({ _id: -1 })
    .limit(100)

您可以在以下位置尝试此查询:

获取 type 为 3 的所有文档(不检查状态)或 type 为 0 或 2 且状态不为 0 的值(正如您在查询中所具有的)

此查询与您的查询之间的区别在于您使用的是 $and,那么 type 必须是 3 AND 0 或 2。一个数字不能同时是两个值时间.

db.collection.find({
  $or: [
    {
      $and: [
        {
          type: {
            $in: [
              0,
              2
            ]
          }
        },
        {
          status: {
            $ne: 0
          }
        }
      ]
    },
    {
      type: 3
    }
  ]
})

示例here