How do I update all Mongo documents that have a single field set to 'null', or that doesn't have a value at all?
What I have, but I'm not sure if it's correct:
db.collection.update({name: {$eq: null}}, {$set: {name: 'test'}})
Starting from MongoDB 4.2 you can perform Updates with an Aggregation Pipeline. An aggregation pipeline enables more expressive updates including calculated fields and references to other field values in the same document.
We can use $set and $inc operators to update any field in MongoDB. The $set operator will set the newly specified value while the $inc operator will increase the value by a specified value.
MongoDB fetch documents containing 'null' If we want to fetch documents from the collection "testtable" which contains the value of "interest" is null, the following mongodb command can be used : >db. testtable. find( { "interest" : null } ).
If the name field is not there try:
db.collection.update({"name": {"$exists": false}}, {"$set": {"name": "test"}})
$set
will add a new field with the specified value, provided that the new field does not violate a type constraint.
If it is there and null, or does not have a value set:
db.collection.update({"name": null}, {"$set": {"name": "test"}})
You can combine both queries using $or
as
db.collection.update(
{
"$or": [
{ "name": { "$exists": false } },
{ "name": null }
]
},
{ "$set": { "name": "test" } }
)
For MongoDB 3.2 and above, use updateMany()
which updates multiple documents within the collection based on the filter:
db.collection.updateMany(
{
"$or": [
{ "name": { "$exists": false } },
{ "name": null }
]
},
{ "$set": { "name": "test" } }
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With