如何在MongoDB中的所有文档中添加具有增量值的新键? [英] How to add a new key with increment value to all documents in MongoDB?

查看:131
本文介绍了如何在MongoDB中的所有文档中添加具有增量值的新键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收藏了50份文件.可以添加一个键(所有键都相同),并且该键的值从1到50递增.例如,第一个文档具有一个键:myId = 1,第二个文档myId = 2和很快.

I have collection with 50 documents. Is is possible to add one key (the same to all of them) and the value of this key is increment from 1 to 50. I mean for example the first document have a key: myId=1 , the second document myId=2 and so on.

推荐答案

您可以在shell内编写脚本以循环浏览所有文档,并为每个文档运行更新查询以添加新字段.

You can write a script inside the shell to loop through all the documents and run an update query for each document to add a new field.

这是将字段添加到集合中的方法: 向MongoDB中的集合添加新字段

This is how you could add a field to collection: Add new field to a collection in MongoDB

请参阅上面我写的链接,它可能会有所帮助

Referring the link above I wrote this, it should probably help

var i = 0;
db.collection.find().forEach(function(myDoc) {
    db.collection.update(myDoc, {$set : {"myId": i++ }}, false, true);  
});

这篇关于如何在MongoDB中的所有文档中添加具有增量值的新键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆