'Replacing $ifNull with $cond in MongoDB aggregation

I am thinking of migrating my app from MongoDB 3.6 to AWS DocumentDB. I am checking to see if everything is supported and I found $ifNull (aggregation) in the code. DocumentDB does not support $ifNull.

For a sample set of documents:

[
  { "hostname": "foo", "name": "a", "is_valid": true },
  { "hostname": "foo", "name": "b", "is_valid": false },
  { "hostname": "foo", "name": "c" }
]

I want to group document by the hostname field and if the is_valid field does not exist, make it true. This is the current aggregation query:

{
  $group: {
    _id: "$hostname",
    boxes: {
      $push: {
        name: "$name",
        is_valid: { $ifNull: ["$is_valid", true]}
      }
    }
  }
}

It returns:

{
  "_id": "foo",
  "boxes": [
    { "name": "a", "is_valid": true },
    { "name": "b", "is_valid": false },
    { "name": "c", "is_valid": true }
  ]
}

This is what I have tried:

{
  $group: {
    _id: "$hostname",
    boxes: {
      $push: {
        name: "$name",
        is_valid: { $cond: [{$ne: ["$is_valid", null]}, "$is_valid", true]}
      }
    }
  }
}

But that returns:

{
  "_id": "foo",
  "boxes": [
    { "name": "a", "is_valid": true },
    { "name": "b", "is_valid": false },
    { "name": "c" }
  ]
}

How can I translate $ifNull into an equivalent $cond?



Solution 1:[1]

Changing $ne to $gt works.

{ 
  $group: {
    _id: "$hostname",
    boxes: {
      $push: {
        name: "$name",
        is_valid: { $cond: [{$gt: ["$is_valid", null]}, "$is_valid", true]}
      }
    }
  }
}

If someone knows why this works, I would feel better understanding it more.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BennyMcBenBen