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?
Use $ifNull
$project: {
date: 1,
name: "$person.name",
age: { $ifNull: [ "$person.age", "null" ] }
}
You can find more about it here
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" ] }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With