mongodb循环收集+;保存时,对象多次返回

mongodb循环收集+;保存时,对象多次返回,mongodb,Mongodb,我正在编写一个相当大的迁移,有以下代码(coffeescript): 出现了一些错误。但它们发生在已处理的用户上: user_ok: user_1234 #many logs user_error: user_1234 ... 为什么循环会接受已处理的对象? 我最后做了: backup = { users: [] } db.users.find().forEach (user)-> try #some code changing the user depending o

我正在编写一个相当大的迁移,有以下代码(coffeescript):

出现了一些错误。但它们发生在已处理的用户上:

 user_ok: user_1234
 #many logs
 user_error: user_1234 ...
为什么循环会接受已处理的对象?

我最后做了:

backup = { users: [] }
db.users.find().forEach (user)->
  try
    #some code changing the user depending on the old state
    backup.users.push user
    print "user_ok: #{user._id}"
  catch error
    print "user_error: #{user._id}, error was #{error}"
#loop backup and save

现在效果不错,但看起来很奇怪。请问这一切背后的意义是什么?

当你修改一个对象时,它可能会被数据库移动。数据库需要特别注意记住哪些对象已经被访问过。如果调用此功能,您可以使用

db.collection.find().snapshot()
但是,即使这样也不能保证在游标迭代期间插入或删除的对象。文档链接中还解释了一些注意事项

另一个选项是对不变的唯一索引执行
$orderby
。理想情况下,该索引也是单调的,因此如果您使用objectid作为主键,那么
\u id
字段非常方便,如

db.collection.find().sort({"_id" :1});
db.collection.find().sort({"_id" :1});