Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

How to remove a column from a mongo db collection?

For example: I have a collection with fields as below.

{ 
    name: 'book',
    mobile:'7777777777',
    email:'abc@gmail.com'
},
{ 
    name: 'pen',
    mobile:'8888888888',
    email:'abc@gmail.com'
}

Here in this collection, I don’t want the email field anymore.

I want the collection without “email” field as below.

{ 
    name: 'book',
    mobile:'7777777777'
},
{ 
    name: 'pen',
    mobile:'8888888888'
}

Is it possible?

Hi @lalitha_devi and welcome to the community forums.

You want to use the $unset operator.

> db.collection.find()
{ "_id" : ObjectId("5edaf777cdb02689803b0b8b"), "name" : "book", "mobile" : "7777777777", "email" : "abc@gmail.com" }
{ "_id" : ObjectId("5edaf78dcdb02689803b0b8c"), "name" : "pen", "mobile" : "8888888888", "email" : "abc@gmail.com" }
> db.collection.updateMany({}, {"$unset": {"email": 1}})
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
> db.collection.find()
{ "_id" : ObjectId("5edaf777cdb02689803b0b8b"), "name" : "book", "mobile" : "7777777777" }
{ "_id" : ObjectId("5edaf78dcdb02689803b0b8c"), "name" : "pen", "mobile" : "8888888888" }
>

Note the above will remove the email field from all documents which is what is sounds like what you want. If you only want to do this on select documents, then you would need to change the {} portion to contain the proper match for the documents you want to update.

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.