1

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)
1

2 Answers 2

2

Thinking that you need an update with the aggregation pipeline.

And use $ifNull operator.

db.users.update({},
[
  {
    "$set": {
      "pre": {
        $ifNull: [
          "$pre",
          "null"
        ]
      },
      "calc": {
        $ifNull: [
          "$calc",
          "null"
        ]
      }
    }
  }
],
false,
true
)

Sample Mongo Playground

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply. I am getting an error TypeError: upsert must be True or False
Not PyMongo developer, but your code should be: db.users.update({}, [...], false, true). which [...] is the aggregation pipeline.
In pymongo this is not working. Unfortunately I am working with pymongo. ` $ifNull: [ "$pre", "null" ]` This is considered as an array in pymongo. This replaces every pre and calc field with an array object
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.