MongoDB - Projecting a field that doesn't always exist

你。 提交于 2019-12-23 08:28:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!