在 MongoDB $cond 中使用 $exists

Using $exists in MongoDB $cond

作为背景,我必须在集合中创建一个字段,但前提是另一个已知字段(数组)不为空。我正在尝试使用 $and 和一些条件制作布尔过滤器:

$set: {
  clientsAllowed: {
            $cond: {
              if: {
                $and: [
                  {
                    businessAllowed: { $exists: true },
                  },
                  {
                    businessAllowed: { $type: "array" },
                  },
                  {
                    businessAllowed: { $ne: [] },
                  },
                ],
              },
              then: [...],
              else: [...],
            },
          }
}

但是我得到这个错误:

Invalid $set :: caused by :: Unrecognized expression '$exists'

$exists 格式有误吗?或者是$and阶段?有什么想法吗?

为 businessAllowed 输入 cond 就足够了。您不需要检查是否存在。

db.collection.aggregate([
  {
    $set: {
      clientsAllowed: {
        $cond: {
          if: {
            $and: [
              {
                "$eq": [
                  {
                    $type: "$businessAllowed"
                  },
                  "array"
                ]
              },
              {
                $ne: [
                  "$businessAllowed",
                  []
                ]
              }
            ]
          },
          then: [],
          else: []
        }
      }
    }
  }
])

mongoplayground