简体   繁体   English

在mongodb shell JavaScript forEach函数中编写关注

[英]Write concern in mongodb shell javascript forEach function

The mongo shell defaults to safe writes, which from my understanding happens at the end of every carriage return. mongo shell默认为安全写入,据我了解,这是在每次回车结束时发生的。 What if you have code in a loop like this: 如果您在这样的循环中有代码怎么办:

db.coll1.find().forEach(function(doc){
    db.coll2.update({"blah": doc._id}, {$set: {"blahblah": doc.value}});
});

Does the db.getLastError() occur for every single update or only at the very end of the for loop on the last update? db.getLastError()是针对每个单个更新发生还是仅在最后一次更新的for循环的最后出现? Or does it happen at the end of the for loop for every updated document, all at one time? 还是在每次更新的文档的for循环结束时一次发生?

The shell actually has w:1 (safe writes) when in interactive mode, when running in a loop it will not call getLastError until the end. 处于交互模式时,shell实际上具有w:1 (安全写入),当在循环中运行时,它直到结束才调用getLastError

As reference you can actually see this comment by @Asya who works for MongoDB Inc. 作为参考,您实际上可以在MongoDB Inc.工作的@Asya看到此评论。

the shell uses safe in that it called getLastError after every "command" (ie carriage return). 外壳使用安全机制是因为它在每个“命令”(即回车)之后都调用了getLastError。 If you are writing data, say, in a loop then GLE will only be called once at the end. 例如,如果要写数据,则在循环中,GLE在最后只会被调用一次。 Provide more details about how you plan to populate collection from the shell - maybe the right thing will already happen 提供有关如何计划从Shell填充集合的更多详细信息-也许正确的事情已经发生

Setting MongoDB's write concern in shell / shell script 在shell / shell脚本中设置MongoDB的写关注

Adding to that answer from Sammaye, if you wanted to call GLE after each update call you would do something like this: 除了来自Sammaye的答案外,如果您希望在每次更新调用后调用GLE,您将执行以下操作:

db.coll1.find().forEach(function(doc){
    db.coll2.update({"blah": doc._id}, {$set: {"blahblah": doc.value}}, true);
    if(db.getLastError(1)){
        printjson(db.getLastError(1)); 
        printjson("failed to update ID: "+doc._id)
    }; 
});

You'll get a dupe error at the end of the loop because of the carriage return if the last op fails, but otherwise it's pretty much what you would expect. 如果最后一次操作失败,则由于回车而在循环末尾会出现重复错误,但是这几乎就是您所期望的。 If you want an easy test to reproduce just set the value field to be a string, then use $inc instead of $set - that will fail on non-numerics. 如果您想要简单的测试来重现,只需将value字段设置为字符串,然后使用$inc而不是$set set-在非数字类型上会失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM