Reputation: 537
I am querying and retrieving all data from a collection to json . The collection has 50 fields.But all 50 fields are not filled in the records. When I retrieve the record to json ,I am getting only existing fields .. For example if name is not there in the document,it wont be there.. I want it to come as {'name':'null'}.
As there are 50 fields,it is difficult to do a manual check..
Upvotes: 0
Views: 39
Reputation:
You might need to use aggregation to overcome this issue. $addFields
will do this for you. But keep in mind that you need to add all the keys in your condition. This is the only way, I could think of to achieve your result.
db.collection.aggregate([
{
$addFields: {
name: {
$cond: [ { $type: 'string' }, '$name', 'null' ]
},
age: {
$cond: [ { $type: 'number' }, '$age', 'null' ]
},
/* ...other fields */
}
}
])
These will overwrite the existing fields, for the value you want.
Upvotes: 1