querydrill

Learn ›Advanced aggregation ›Array and conditional expressions

$ifNull and missing fields

$ifNull$project

Optional fields are normal in MongoDB, and arithmetic on a field that is not there does not do what you want. $ifNull substitutes a default, and it belongs anywhere you compute with a field that will not always exist.

Suppose:

{
  name: "Denish"
}

No nickname.

You want:

nickname = "Anonymous"

if it doesn’t exist.

{
  $project: {
    name: 1,

    nickname: {
      $ifNull: [
        "$nickname",
        "Anonymous"
      ]
    }
  }
}

Mental model:

nickname ?? "Anonymous"

Useful when dealing with optional fields.

Try it

Half the orders in the sample data have no rating:

db.orders.aggregate([
  {
    $project: {
      rating: 1,
      ratingOrDefault: { $ifNull: ["$rating", "not rated"] }
    }
  },
  { $limit: 6 }
])

Compare the two fields on the rows where rating is missing. The first one is simply absent from the output - that is what your arithmetic would have been handed.

Practise this

1 exercise