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.
2 Answers
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.
Comments
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.
2 Comments
findAndModify does support remove, which I mentioned in this answer. It does serve a purpose, as you can't be completely sure that the document (or even the criteria) will not change between the find() and remove() operations in your example..find() return an array of objects? Wouldn't that make doc._id = doc[0]._id or something like that?
m making a logging feature and i need the previous and new state of the document. In this case i already have an identifier of the document i want to remove. Im looking for a concrete solution like this because i`m trying to optimize as much as possible because this will be done on all of the remove "queries" in the applicationll have to modify my application not to use documents which have delete flag. It seems that ill have to use select (synchronous (puke)) :D Thanks