Issue
I am currently implementing a Mongo ChangeStream poller in which I would like to monitor a collection for any changes. I was originally intending to write the updates to a change log and trigger some other actions. However, I found out that the save() call in Spring Data performs a document replace instead of update. Therefore, I only have access to the new document instead of the delta as would occur during an update.
There are two options I see:
- Replace the
savecall with something likeupdateOne - Update the collection with
changeStreamPreAndPostImagesset totrueand diff the two documents
If I go with option 1, I'm wondering if there is an easy way to generate the update query dynamically based on the existing document and the updated document? Prior to the save/update I fetch the current document and update the values before saving again. I couldn't find any built in support. I'm guessing I'd have to take a reflection based approach, but I wanted to see if there's any existing solutions already.
Solution
Ultimately, I went with option 2 as it turned out to be quite easy to enable changeStreamPreAndPostImages on application start up. I created an extension on the mongo client:
fun MongoDatabase.enablePreImageChangeStream(collection: String) {
this.runCommand(
BsonDocument.parse(
"""
{
"collMod": "$collection",
"changeStreamPreAndPostImages": { "enabled": true }
}
"""
)
)
}
Then on application start up I did:
@Configuration
class ChangeStreamConfiguration(
private val mongoTemplate: MongoTemplate,
) {
init {
mongoTemplate.db.enablePreImageChangeStream("<collection name here>")
}
}
Answered By - fbailey
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.