Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove attribute from MongoDb Object?

Tags:

mongodb

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.

like image 559
johndoe Avatar asked Oct 07 '10 01:10

johndoe


People also ask

Which operator is used to remove attributes from an object in MongoDB?

The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

What is remove in MongoDB?

MongoDB's remove() method is used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag. deletion criteria − (Optional) deletion criteria according to documents will be removed.

How do I delete a nested object in MongoDB?

To remove an element from a doubly-nested array in MongoDB document, you can use $pull operator. Now field "UserZipCode": "20010" has been removed from a doubly-nested array.


1 Answers

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.

like image 70
Telmo Dias Avatar answered Oct 23 '22 23:10

Telmo Dias