skip to Main Content

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


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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search