Removing

Removing Objects from a Collection

To remove objects from a collection, use the remove() function in the mongo shell. (Other drivers offer a similar
function, but may call the function "delete". Please check your driver's documentation ).

remove() is like find() in that it takes a JSON-style query document as an argument to select which documents are removed. If you call remove() without a document argument, or with an empty document {}, it will remove all documents in the collection. Some examples :

db.things.remove({});    // removes all
db.things.remove({n:1}); // removes all where n == 1

The most efficient method to delete a specific document is to use item's document _id value as a criteria:

> // myobject is some document that is in our db.things collection
> db.things.remove({_id: myobject._id});

Note that passing an entire document to remove() would work, but is inefficient as in that case we are basically specifying every single field of the document as part of the query expression.

> db.things.remove(myobject); // don't do this

Isolation

If a simultaneous update (on the same collection) grows an object which matched the remove criteria, the updated object may not be removed (as the operations are happening at approximately the same time, this may not even be surprising). In situations where this is undesireable, pass {$atomic : true} in your filter expression:

db.videos.remove( { rating : { $lt : 3.0 }, $atomic : true } )

The remove operation is then isolated – however, it will also block other operations while executing. The collection must be unsharded to use this option.


Labels

truncate truncate Delete
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

PLEASE POST QUESTIONS IN THE FORUMS: http://groups.google.com/group/mongodb-user. Post tips and clarifications here.

blog comments powered by Disqus