Reputation: 450
Is there something like findAndModify() but for remove() in mongodb. I need to remove a document and in the same time to retrieve its contents. I`m searching for a solution that does it in one "query" to the mongodb server. Thanks.
Upvotes: 2
Views: 518
Reputation: 6922
MongoDB's findAndModify
command supports a remove
option. It is mutually exclusive with the update
option, so you would specify remove
instead of providing update
with a "new object" (atomic modifiers or a replacement document). Also, while the new
option would normally allow you to return the document in its pre- or post-update state, it doesn't apply to remove
.
Upvotes: 3
Reputation: 47956
I do not believe that mongo has this functionality. I also don't really see why you would need this. If you identify your documents correctly (and use indexes where possible), the remove action will be very quick and very efficient.
However, once you have retrieved the document you want to remove, you can use it's _id
attribute to find it again for removal.
var doc = db.data.find( { "please": "delete me" } );
db.data.remove( { "_id": doc._id } );
Mongo indexes your collections by _id
as a default, so when you use it to identify a document (as we are doing with remove), the actual operation is very efficient.
Upvotes: 0