检查mongodb聚合中的空条件

dced5bon  于 2022-12-03  发布在  Go
关注(0)|答案(1)|浏览(131)

bookSchema集合:

[
    {
        _id: ObjectId("637d05dc32428ed75ea08d09"),
        book_details: {
            book_subscription: null,
            book_auth: 'Amber'
        },
        book_name: 'random123'
    },
    {
        _id: ObjectId("637d0673ce0f17f6c473dee2"),
        book_details: {
            book_subscription: ObjectId('637d06a545a17f0e686ecf3a'),
            book_auth: 'Shurya'
        },
        book_name: 'random321'
    },
    {
        _id: ObjectId("637d069a3d597c8458ebe4ec"),
        book_details: {
            book_subscription: ObjectId('637d06ac82f0760b03fdea0d'),
            book_auth: 'Aman'
        },
        book_name: 'random676'
    },
    {
        _id: ObjectId("637d06c05b32d503007bcb54"),
        book_details: {
            book_subscription: null,
            book_auth: 'Saurav'
        },
        book_name: 'random999'
    }
]

如果book_subscription不为空,我希望book_count为1;如果book_subscription为空,我希望book_count为0。
为此我试着说:

db.bookSchema.aggregate([
  {
    "$addFields": {
      "book_count": {
        "$cond": {
          "if": {
            "$ne": [
              "book_details.book_subscription",
              null
            ]
          },
          "then": 1,
          "else": 0
        }
      }
    }
  }
])

但是,即使book_subscription为空,我得到的book_count也是1。
如何检查book_subscription得值是否为空,只有值为得book_subscription计数为1,为空得book_subscription计数为0?
蒙哥达Playground:https://mongoplayground.net/p/Ff4Q43-nSQe

rqqzpn5f

rqqzpn5f1#

一个选项是:

db.bookSchema.aggregate([
  {
    "$addFields": {
      "book_count": {
        "$cond": {
          "if": {
            "$ne": [
              "$book_details.book_subscription",
              null
            ]
          },
          "then": 1,
          "else": 0
        }
      }
    }
  }
])

了解它在playground example上的工作原理
另一个是:

db.bookSchema.aggregate([
  {
    "$addFields": {
      "book_count": {
        "$toInt": {
          "$toBool": {
            "$ifNull": [
              "$book_details.book_subscription",
              0
            ]
          }
        }
      }
    }
  }
])

了解它在playground example- bool上的工作原理

相关问题