MongoDb unique enough identifier - Is it safe to use $pop to remove elements of an array in mongo db?
I'm concerned about using $pop to remove elements of an array (embedded document) in mongodb for 2 main reasons:
- I don't know if the order of the array is static. Is it possible for the array to be returned/stored in a different order?
- What if another user removes an index of the a less or equal value before I remove mine? That would cause the wrong data to be removed.
I know I can use $pull, but the issue with that is that I may have to use the entire embeded object for the criterea, I want to be able use somesort of "uniqe enough" (this may be another question entirely) identifier to use when dealing with embeded objects and its position in the array seems to be logical choice.
If it is indeed "unsafe" to use $pop I have thought two possible solutions for a "unique enough" identifier.
- Add a new instance of MongoId to each embedded object at time of insertion. The issue with this is now loos the $set's feature of not inserting a duplicate entry. You would have to check for duplicates before insertion.
- json_encode the the new entry, then md5 hash that json string. This may be the best solution because it will ensure that the identifier is unique to that record, but if you try to insert the same entry, it will indeed still be the same so $set will ignore it.
So I guess my question is two part: Is it safe to use $pop when removing items from an array. If not, what is the best practice for adding a unique enough identifiers to embedded documents?
开发者_运维技巧(it may or may not be relevant that I'm using PHP)
For 1, the order of the array won't change if you manipulate it in the good way.
For 2, you can use an "Update if current" strategy (optimistic locking): http://www.mongodb.org/display/DOCS/Atomic+Operations#AtomicOperations-%22UpdateifCurrent%22 Add a version field to your document that you will increment at each modification (Doctrine MongoDB ODM can do this for you).
精彩评论