In order to get the full document in a watcher after deleting the document you need to enable collMod on the collection. See the below 4 steps.
1.Download mongoshell https://www.mongodb.com/try/download/shell
2.Run mongoshell and paste your connection string with an admin user and press enter (create a temporary admin if you need to) Looks like this:
mongodb+srv://user:QkKvrDtL0yZFERGA@showspace-cluster.1yyql9v.mongodb.net/my-db`
3.In mongoshell run the following command to change the 'collMod' for your collection - swop out my collection 'ProductReview' for your collection
db.runCommand({collMod: "ProductReview", changeStreamPreAndPostImages: {enabled: true}})
4.Now in your app you can setup a change stream and access the deleted document like so (the below code is nodejs)
const client = new MongoClient(env.DATABASE_URL);
const database = client.db("my_database");
const reviews = database.collection("ProductReview");
// 'fullDocumentBeforeChange' is the magic here
const changeStream = reviews.watch([], {
fullDocument: "updateLookup",
fullDocumentBeforeChange: "required"
});
changeStream.on("change", async (event) => {
let document;
if (event.operationType === 'delete') {
document = event.fullDocumentBeforeChange;
} else {
document = event.fullDocument;
}
// do some stuff with the document
});
Documentation:
https://www.mongodb.com/docs/v6.0/reference/operator/aggregation/changeStream/
Related questions:
- https://jira.mongodb.org/browse/SERVER-36941
- https://jira.mongodb.org/browse/SERVER-56074
- https://stackoverflow.com/questions/56939610/how-to-get-fulldocument-from-mongodb-changestream-when-a-document-is-deleted
- https://www.mongodb.com/community/forums/t/change-stream-fulldocument-on-delete/15963
- https://www.mongodb.com/try/download/shell
Top comments (0)