Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 973
Peter Sampson Avatar asked Apr 01 '15 18:04

Peter Sampson


2 Answers

Use $ifNull

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

You can find more about it here

like image 94
karthik manchala Avatar answered Oct 06 '22 02:10

karthik manchala


This is where $ifNull expression comes into the fray. From the docs, $ifNull:

Evaluates an expression and returns the value of the expression if the expression evaluates to a non-null value. If the expression evaluates to a null value, including instances of undefined values or missing fields, returns the value of the replacement expression.

In your case, the following will use the $ifNull expression to return either the non-null $person.age field value or the string "Unspecified" if the age field is null or does not exist:

 $project: {
     date: 1,
     name: "$person.name",         
     age: { $ifNull: [ "$person.age", "Unspecified" ] }
 }    
like image 40
chridam Avatar answered Oct 06 '22 01:10

chridam