Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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      } } 
like image 282
TIMEX Avatar asked Jul 27 '11 22:07

TIMEX


People also ask

How do I remove a field from a document in MongoDB?

In MongoDB, you can use the $unset field update operator to completely remove a field from a document. The $unset operator is designed specifically to delete a field and its value from the document.

How do you remove a field?

Delete a field from a table. In the Navigation Pane, right-click the table, and then click Design View. In the table design grid, select the field that you want to delete, and then press DEL.

How do you delete an element in MongoDB?

To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

How do I remove all data from a collection in MongoDB?

To delete all documents in a collection, pass an empty document ( {} ). Optional. To limit the deletion to just one document, set to true . Omit to use the default value of false and delete all documents matching the deletion criteria.


1 Answers

Try this: If your collection was 'example'

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

Refer this:

http://www.mongodb.org/display/DOCS/Updating#Updating-%24unset

UPDATE:

The above link no longer covers '$unset'ing. Be sure to add {multi: true} if you want to remove this field from all of the documents in the collection; otherwise, it will only remove it from the first document it finds that matches. See this for updated documentation:

https://docs.mongodb.com/manual/reference/operator/update/unset/

Example:

db.example.update({}, {$unset: {words:1}} , {multi: true}); 
like image 62
Shaunak Avatar answered Sep 20 '22 12:09

Shaunak