如何在MongoDB中获取删除的文档?

问题描述:

能否获得从MongoDB中删除的文档?

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

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

谢谢!

可以,但是需要使用其他命令.您正在寻找 findAndModify命令.

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

如果将选项设置为{query: ..., remove: true, new: false},则将删除单个文档并返回删除的文档.

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

一些注释:

  • new是许多语言的关键字,请确保正确包装标志的文本.
  • findAndModify仅适用于单个文档.删除_id很好,但是对于远程删除则不好.
  • 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.