28

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.

1
  • 4
    Found the answer => delete customer.MiddleName Commented Oct 7, 2010 at 1:54

1 Answer 1

60

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.

Sign up to request clarification or add additional context in comments.

4 Comments

i have run this command on a db of 20million records. Its been 14 minutes already. Deleting one field.
Yep, I'm not surprised. Can you suggest a better way for a database designed to be schema-free?
The argument signature for db.collection.update was change in 2.2 : docs.mongodb.org/manual/reference/method/db.collection.update
Note that checking if the field exist is not necessary: db.collection.update({}, { $unset: { "properties.service": 1 } }, { multi: true })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.