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

编程入门 行业动态 更新时间:2024-10-27 21:23:16
本文介绍了mongodb使用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更新所有文档的密钥

本文发布于:2023-10-16 15:50:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1498025.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:密钥   文档   mongodb   forEach

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!