I have a sample collection of documents in mongo db like below
[{"name":"hans","age":30,"test":"pass","pre":"no","calc":"no"},
{"name":"abs","age":20,"test":"not_pass","pre":"yes","calc":"no"},
{"name":"cdf","age":40,"test":"pass"},
{"name":"cvf","age":30,"test":"not_pass","pre":"no","calc":"yes"},
{"name":"cdf","age":23,"test":"pass"},
{"name":"asd","age":35,"test":"not_pass"}]
For some documents the fields pre
and calc
are not present. I want to add those two fields to the documents which dont have those fields with value null
for both "pre":"null", "calc":"null"
.
The final document should look like
[{"name":"hans","age":30,"test":"pass","pre":"no","calc":"no"},
{"name":"abs","age":20,"test":"not_pass","pre":"yes","calc":"no"},
{"name":"cdf","age":40,"test":"pass","pre":"null","calc":"null"},
{"name":"cvf","age":30,"test":"not_pass","pre":"no","calc":"yes"},
{"name":"cdf","age":23,"test":"pass","pre":"null","calc":"null"},
{"name":"asd","age":35,"test":"not_pass","pre":"null","calc":"null"}]
I tried this way but didnt work.
db.users.update({}, { "$set" : { "pre":"null","calc":"null" }}, false,true)
2
Answers
Thinking that you need an update with the aggregation pipeline.
And use
$ifNull
operator.Sample Mongo Playground
The easiest option is to run this query for every missing field that you have , for example for pre:
Playground