Search code examples
mongodbnullprojection

Projecting a field that doesn't always exist


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 have 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?


Solution

  • Use $ifNull

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

    You can find more about it here