MongoDB - Projecting a field that doesn't always exist

Peter Sampson picture Peter Sampson · Apr 1, 2015 · Viewed 10.5k times · Source

Is there a way to project fields that may or may not exist? Such as having it defined as null or undefined?

For instance, I am doing a query with:

      $project: {
         date: 1,
         name: "$person.name",
         age: "$person.age"
      }              

Not all documents are guaranteed to have a $person.age, but instead of the ones without an age being returned as { date: Today, name: "Bill" }, I would like it to say { date: Today, name: "Bill", age: null }. Or something similar.

Is there a better way than just iterating through the data afterwards and creating the fields if they don't exist?

Answer

karthik manchala picture karthik manchala · Apr 1, 2015

Use $ifNull

  $project: {
     date: 1,
     name: "$person.name",
     age: { $ifNull: [ "$person.age", "null" ] }
  }  

You can find more about it here