Home > OS >  Check for null condition in mongodb aggregation
Check for null condition in mongodb aggregation

Time:11-23

bookSchema collection:

[
    {
        _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'
    }
]

I want the book_count to be 1 if book_subscription is not null and 0 if book_subscription is null.

For this I tried as:

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

But the book_count I get is 1 eventhough book_subscription is null.

How to check whether the value of book_subscription is null and get the count as 1 only for book_subscription with value and 0 for book_subscription, null?

Mongodb Playground: https://mongoplayground.net/p/Ff4Q43-nSQe

CodePudding user response:

One option is:

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

See how it works on the playground example

Another one is:

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

See how it works on the playground example- bool

  • Related