How to get removed document in MongoDB?

前端 未结 2 876
再見小時候
再見小時候 2020-12-04 01:58

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

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

2条回答
  •  盖世英雄少女心
    2020-12-04 02:22

    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.

提交回复
热议问题