Mrugesh
Mrugesh

Reputation: 4517

Check and update if the field doesn't exists in collection

I have a few documents in the collection orders where is_show is already set with value true/false for the new documents .

Now what I want is , for the past documents , it should insert the key
is_show with value false for particular order type . For that I have written the query as shown below :

db.getCollection("orders").update({"order_type":1}, {$set: {"is_show": false}}, false, true)

But some how it is adding is_show false for the new as well as old documents .

so how can I modify the query to achieve that functionality?

Upvotes: 2

Views: 116

Answers (1)

Ashh
Ashh

Reputation: 46451

You can use $exists query operator to check whether the document contains that field or not

db.getCollection("orders").update(
  { "order_type": 1, "is_show": { "$exists": false }},
  { "$set": { "is_show": false }},
  { "multi": true }
)

Upvotes: 4

Related Questions