How to delete a document in MongoDB?

Can I get a document that has been deleted from MongoDB?

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

Thanks!

+8
mongodb
source share
2 answers

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

If you set the parameters {query: ..., remove: true, new: false} , you will delete one document and return the deleted document.

Some notes:

  • new is a keyword in many languages, make sure that you have correctly entered the flag text.
  • findAndModify will only work with one document. This is great for removing _id , but not suitable for remote ranges.
+10
source share
 db.collection('mycollection').findOneAndDelete({ id: '123456' }, function (error, response) { response.value;// returns the deleted object, but no longer exists in the database }); 
+2
source share

All Articles