[mongodb] How to remove a field completely from a MongoDB document?

{ 
    name: 'book',
    tags: {
        words: ['abc','123'],
        lat: 33,
        long: 22
    }
}

Suppose this is a document. How do I remove "words" completely from all the documents in this collection? I want all documents to be without "words":

 { 
     name: 'book',
     tags: {
         lat: 33,
         long: 22
     }
}

This question is related to mongodb mongodb-query database

The answer is


Because I kept finding this page when looking for a way to remove a field using MongoEngine, I guess it might be helpful to post the MongoEngine way here too:

Example.objects.all().update(unset__tags__words=1)

By default, the update() method updates a single document. Set the Multi Parameter to update all documents that match the query criteria.

Changed in version 3.6. Syntax :

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ]
   }
)

Example :

db.getCollection('products').update({},{$unset: {translate:1, qordoba_translation_version:1}}, {multi: true})

In your example :

db.getCollection('products').update({},{$unset: {'tags.words' :1}},  {multi: true})

In mongoDB shell this code might be helpful:

db.collection.update({}, {$unset: {fieldname: ""}} )

To reference a package and remove various "keys", try this

db['name1.name2.name3.Properties'].remove([
{
     "key" : "name_key1"
},
{
     "key" : "name_key2"
},
{
     "key" : "name_key3"
}
)]

{ name: 'book', tags: { words: ['abc','123'], lat: 33, long: 22 } }

Ans:

db.tablename.remove({'tags.words':['abc','123']})


And for mongomapper,

  • Document: Shutoff
  • Field to remove: shutoff_type

Shutoff.collection.update( {}, { '$unset' => { 'shutoff_type': 1 } }, :multi => true )


db.example.updateMany({},{"$unset":{"tags.words":1}})

We can also use this to update multiple documents.


Checking if "words" exists and then removing from the document

    db.users.update({"tags.words" :{$exists: true}},
                                           {$unset:{"tags.words":1}},false,true);

true indicates update multiple documents if matched.


The solution for PyMongo (Python mongo):

db.example.update({}, {'$unset': {'tags.words':1}}, multi=True);

To remove or delete field in MongoDB

  • For single Record

    db.getCollection('userData').update({}, {$unset: {pi: 1}})
    
  • For Multi Record

    db.getCollection('userData').update({}, {$unset: {pi: 1}}, {multi: true})
    

In the beginning, I did not get why the question has a bounty (I thought that the question has a nice answer and there is nothing to add), but then I noticed that the answer which was accepted and upvoted 15 times was actually wrong!

Yes, you have to use $unset operator, but this unset is going to remove the words key which does not exist for a document for a collection. So basically it will do nothing.

So you need to tell Mongo to look in the document tags and then in the words using dot notation. So the correct query is.

db.example.update(
  {},
  { $unset: {'tags.words':1}},
  false, true
)

Just for the sake of completion, I will refer to another way of doing it, which is much worse, but this way you can change the field with any custom code (even based on another field from this document).


Starting Mongo 4.2, it's also possible to use a slightly different syntax:

// { name: "book", tags: { words: ["abc", "123"], lat: 33, long: 22 } }
db.collection.update({}, [{ $unset: ["tags.words"] }], { many: true })
// { name: "book", tags: { lat: 33, long: 22 } }

The update method can also accept an aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline).

This means the $unset operator being used is the aggregation one (as opposed to the "query" one), whose syntax takes an array of fields.


you can also do this in aggregation by using project at 3.4

{$project: {"tags.words": 0} }


I was trying to do something similar to this but instead remove the column from an embedded document. It took me a while to find a solution and this was the first post I came across so I thought I would post this here for anyone else trying to do the same.

So lets say instead your data looks like this:

{ 
  name: 'book',
  tags: [
    {
      words: ['abc','123'],
      lat: 33,
      long: 22
    }, {
      words: ['def','456'],
      lat: 44,
      long: 33
    }
  ]
}

To remove the column words from the embedded document, do this:

db.example.update(
  {'tags': {'$exists': true}},
  { $unset: {'tags.$[].words': 1}},
  {multi: true}
)

or using the updateMany

db.example.updateMany(
  {'tags': {'$exists': true}},
  { $unset: {'tags.$[].words': 1}}
)

The $unset will only edit it if the value exists but it will not do a safe navigation (it wont check if tags exists first) so the exists is needed on the embedded document.

This uses the all positional operator ($[]) which was introduced in version 3.6


Examples related to mongodb

Server Discovery And Monitoring engine is deprecated Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Failed to start mongod.service: Unit mongod.service not found db.collection is not a function when using MongoClient v3.0 MongoError: connect ECONNREFUSED 127.0.0.1:27017 MongoDB: How To Delete All Records Of A Collection in MongoDB Shell? How to resolve Nodejs: Error: ENOENT: no such file or directory How to create a DB for MongoDB container on start up?

Examples related to mongodb-query

How to join multiple collections with $lookup in mongodb $lookup on ObjectId's in an array how to convert string to numerical values in mongodb How to convert a pymongo.cursor.Cursor into a dict? Mongodb find() query : return only unique values (no duplicates) How to list all databases in the mongo shell? Printing Mongo query output to a file while in the mongo shell MongoDB "root" user How to query nested objects? How to filter array in subdocument with MongoDB

Examples related to database

Implement specialization in ER diagram phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' cannot be loaded Room - Schema export directory is not provided to the annotation processor so we cannot export the schema SQL Query Where Date = Today Minus 7 Days MySQL Error: : 'Access denied for user 'root'@'localhost' SQL Server date format yyyymmdd How to create a foreign key in phpmyadmin WooCommerce: Finding the products in database TypeError: tuple indices must be integers, not str