Ashish Bairwa
Ashish Bairwa

Reputation: 775

Updating all the documents where the key doesn't exist or is set to null - Mongodb

I have a collection where the documents are like:

[
  {
    name: 'Mario',
    powers: ['highjump'],
    locations: {
      town: 'downtown'
    }
  },
  {
    name: 'Batman',
    powers: ['blades', 'superkicks'],
    locations: {
      town: 'downtown'
    }
  },
  {
    name: 'Ironman',
    powers: ['lasers'],
    locations: null,
  },
  {
    name: 'Superman',
    powers: ['kryptonslash'],
  },
]

I want to update all the documents within this collection with the:

locations: {
  town: 'downtown'
}

wherever locations are either null or don't exist. I'm aware of $set and $exists to be used and here is my attempt anyways.

db.collection.update({
  locations: {
    $or: [
      $exists: false,
      $eq: null
      ]
  }
},
{
  $set: {
    locations: {
      town: 'downtown'
    }
  }
})

But it's not working as expected, I'm not sure how to update incase if it doesn't exists within the document at all.

Upvotes: 0

Views: 29

Answers (1)

turivishal
turivishal

Reputation: 36154

Separate the conditions by $or operator, and put multi: true if you are updating multiple documents,

db.collection.update({
  $or: [
    { locations: { $exists: false } },
    { locations: null }
  ]
},
{
  $set: {
    locations: {
      town: "downtown"
    }
  }
},
{ multi: true })

Playground

Upvotes: 1

Related Questions