【问题标题】:Check for null condition in mongodb aggregation检查 mongodb 聚合中的空条件
【发布时间】:2022-11-23 02:07:15
【问题描述】:

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_count 是 1,即使图书订阅为空。

如何检查 book_subscription 的值是否为 null,并仅对有值的 book_subscription 计数为 1,对 book_subscription,null 计数为 0?

Mongodb 游乐场:https://mongoplayground.net/p/Ff4Q43-nSQe

【问题讨论】:

    标签: javascript mongodb


    【解决方案1】:

    一种选择是:

    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 上的工作原理

    【讨论】:

    • 是的,它工作得很好。谢谢您的帮助。只是一个查询,将 $ 符号放在 book_details 前面是如何工作的?
    • 它指的是价值在这把钥匙里面
    • 知道了。谢谢您的帮助。
    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多