问题
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?
回答1:
Use $ifNull
  $project: {
     date: 1,
     name: "$person.name",
     age: { $ifNull: [ "$person.age", "null" ] }
  }  
You can find more about it here
回答2:
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" ] }
 }    
    来源:https://stackoverflow.com/questions/29398260/mongodb-projecting-a-field-that-doesnt-always-exist