Safe+efficient way to modify Mongo objects while iterating over a cursor? Safe+efficient way to modify Mongo objects while iterating over a cursor? mongodb mongodb

Safe+efficient way to modify Mongo objects while iterating over a cursor?


It sounds like what you want is a snapshot query. Here's more info on how to do that:

http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database


Consider using an update command that modifies multiple documents:http://docs.mongodb.org/manual/tutorial/modify-documents/

Also, since you are only modifying some objects, consider using a query that only returns documents that you are actually going to modify rather than scanning the entire collection.

Iterating over the result of a find and modifying objects may seem more convenient and flexible, as you are not limited to what you can do with update operators, and you can write code in your language of choice to modify the document. However, there is the problem you described as well as other limitations:

http://docs.mongodb.org/manual/faq/developers/#faq-developers-isolate-cursors

For example, snapshot queries are not 100% safe, and they cannot be used with sharded collection, so if you later decide to shard, then your solution will break.

If you need to modify a very large number of objects in a more complicated way, maybe map-reduce or the aggregation pipeline can be a way to solve your problem:

http://docs.mongodb.org/manual/core/aggregation-pipeline/

http://docs.mongodb.org/manual/core/map-reduce/