johndoe
johndoe

Reputation: 283

How to remove attribute from MongoDb Object?

I have added MiddleName attribute to my Customer object. Customer is a simple Object() instance. I want to remove this attribute from my object. How can I do that? I am using MongoDb interactive Console.

Upvotes: 28

Views: 27128

Answers (1)

Telmo Dias
Telmo Dias

Reputation: 4168

You should use the $unset modifier while updating:

To delete: (most recent syntax) https://docs.mongodb.com/manual/reference/method/db.collection.update/

db.collection.update(
    {},
    { 
        $unset : { 
            "properties.service" : 1 
        } 
    },
    {
        multi: true
    }
);

Updated thanks to Xavier Guihot comment!

To delete: (only left for reference of the old syntax)

// db.collection.update( criteria, objNew, upsert, multi )

db.collection.update( 
    { 
        "properties.service" : { 
             $exists : true 
         } 
    }, 
    { 
         $unset : { 
             "properties.service" : 1 
         } 
    }, 
    false, 
    true
);

To verify they have been deleted you can use:

db.collection.find( 
    { 
        "properties.service" : { 
            $exists : true
         } 
    } 
).count(true);

Remember to use the multi option as true if you want to update multiple records. In my case I wanted to delete the properties.service attribute from all records on this collection.

Upvotes: 60

Related Questions