mongodb使用forEach更新所有文档的密钥 [英] mongodb update a key to all documents using forEach
问题描述
我想在Mongo
中将所有文档的订单"字段更新为1..2..3..4 .... 34.
I want to update in Mongo
the 'order' field to all of my documents so they will be 1..2..3..4....34.
运行此命令后,它们都具有"order":"34". 我在做什么错了?
After running this, they all have "order": "34". What am I doing wrong?
var i = 1;
db.images.find().forEach(function() {
db.images.update(
{},
{ "$set": {"order": NumberInt(i)} },
{ multi: true }
);
i++;
})
推荐答案
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
这篇关于mongodb使用forEach更新所有文档的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!