Search code examples
pythonmongodbmongodb-queryaggregation-frameworkpymongo

Adding multiple fields to documents in mongodb using pymongo


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)

Solution

  • The easiest option is to run this query for every missing field that you have , for example for pre:

    db.collection.update({
    pre: {
        $exists: false
      }
    },
    {
     "$set": {
       "pre": null
     }
    },
    {
      multi: true
    })
    

    Playground