Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get removed document in MongoDB?

Tags:

mongodb

Is it possible to get the document that was removed from MongoDB?

result = db.things.remove({_id: id})
// is there a result.removedObjects?

Thanks!

like image 522
Michael Spector Avatar asked Jul 23 '12 06:07

Michael Spector


2 Answers

It is possible, but it requires a different command. You are looking for the findAndModify command.

If you set the options to {query: ..., remove: true, new: false}, you will delete a single document and return the removed document.

Some notes:

  • new is a keyword in many languages, ensure that you are wrapping the text of the flag correctly.
  • the findAndModify will only work with a single document. This is fine for deleting _id but not good for ranged removes.
like image 73
Gates VP Avatar answered Nov 01 '22 08:11

Gates VP


db.collection('mycollection').findOneAndDelete({
    id: '123456'
}, function (error, response) {
    response.value;// returns the deleted object, but no longer exists in the database
});
like image 36
evilReiko Avatar answered Nov 01 '22 08:11

evilReiko