Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo update all records with a field that's null

Tags:

mongodb

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'}})
like image 221
reectrix Avatar asked Mar 25 '15 14:03

reectrix


People also ask

Is it possible to update MongoDB field using value of another field?

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.

How do you update a specific field in MongoDB?

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.

How does MongoDB match null values?

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 } ).


1 Answers

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" } }
)
like image 91
chridam Avatar answered Sep 30 '22 13:09

chridam