且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

mongodb使用forEach更新所有文档的密钥

更新时间:2023-01-09 09:08:48

multi : true表示所有与查询匹配的文档都将被更新.您的查询是{},它与所有文档匹配.因此,基本上,您是在每次迭代中更新所有文档的order.

multi : true means all documents matching the query will be updated. And your query is {}, which matches all the documents. So, basically you are updating the order of all the documents in every iteration.

此外,必须启用 snapshot 模式光标上,以确保不会多次返回同一文档.

Also, snapshot mode has to be enabled on the cursor to ensure that the same document isn't returned more than once.

您可以尝试以下方法:

var i = 1;
db.images.find().snapshot().forEach(function(image) {
    db.images.update(
        {"_id" : image._id},
        { "$set": {"order": NumberInt(i)} }
    );
    i++;
})

从性能的角度来看,***使用批量API. 批量写入

From a performance standpoint, it is better to use the bulk APIs. bulkwrite