开发者

MongoDB - Maintain data integrity automatically

开发者 https://www.devze.com 2023-02-06 22:37 出处:网络
I\'m interested in migrating from a relational DB to M开发者_如何学JAVAongoDB for the performance improvements.I would be storing redundant, denormalized data in multiple locations and am wondering if

I'm interested in migrating from a relational DB to M开发者_如何学JAVAongoDB for the performance improvements. I would be storing redundant, denormalized data in multiple locations and am wondering if it is possible to automatically maintain the integrity of data WITHOUT application code.

For example, if I have a User document...

User: { _id: "...", userName: "johndoe", displayName: "John Doe", TotalTasks: 3 }

And then a Task document...

Task: { _id "...", title: "Finish Reports", userID: "...", userName: "johndoe", userDiplayName: "John Doe" }

How can I automatically ensure that userName and displayName stay the same in the appropriate documents? How can I ensure that TotalTasks is updated when new tasks are added or deleted for this user?


You can't enforce these constraints on the server side. However triggers are something that's planned. The only constraint that's currently supported is unique indexes.


Can't enforce them with MongoDB without some outside application coding. The one question I would have above, is why not have Tasks be part of the user document? That would eliminate your consistency issue as you would be able to handle the user and task atomically.

However, assuming you can't, What I have done in the past is use MySQL and a version field to enforce consistency. Each app is different, but the basic gist is as follows:

1) each doc in Mongo has a related row in MySQL. This row in MySql will have the collection, the id of the doc and some auditing info (last changed, who changed, etc.) 2) determine what docs you need to lock and then create a serializable transaction in mysql. 3) update the records in mongo using a Find and update and make sure the version field matches to enforce optimistic concurrency. 4) if everything completes, then commit the transaction in mysql. 5) if something goes wrong, rollback all the operations in mongo that completed. If a rollback can't be completed, shove the info to rollback into a messagequeue and have a separate process that "cleans" up. 6) roll back the mysql transaction

This has to be used sparingly since it adds a lot of overhead to your operations, however, if you embed your documents as I described with the user -> task, you should find that you don't really need to use this except in some outside cases or bulk updates.

0

精彩评论

暂无评论...
验证码 换一张
取 消