Reputation: 775
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
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 })
Upvotes: 1