在mongodb shell上更新forEach [英] Update in forEach on mongodb shell

查看:62
本文介绍了在mongodb shell上更新forEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含2条记录的 aTable 集合:

I have got a collection aTable with 2 records:

 {
    "title" : "record 1",
    "fields" : [ 
        {
            "_id" : 1,
            "items" : [ 
                1
            ]
        },
        {
            "_id" : 2,
            "items" : [ 
                2,3,4
            ]
        },
        {
            "_id" : 3,
            "items" : [ 
                5
            ]
        }
    ]
},

{
        "title" : "record 2",
        "fields" : [ 
            {
                "_id" : 4,
                "items" : [ 
                    7,8,9,10
                ]
            },
            {
                "_id" : 5,
                "items" : [ 

                ]
            },
            {
                "_id" : 6,
                "items" : [ 
                    11,12
                ]
            }
        ]
    }

我想从

items" : [ 11,12 ]

items" : [ 
   {item: 11, key: 0},
   {item:12, key: 0}
]

我使用forEach浏览字段但我无法保存。

i browse fields with forEach but i can't save it.

var t = db.aTable.find();

t.forEach(function( aRow ) {
    aRow.fields.forEach( function( aField ){
        aField.items.forEach( function( item ){
            var aNewItem = { item: parseInt(item), ref: 0 };
            db.aTable.update(item, {$set:aNewItem})
        } )
    } )
});

请帮帮我。非常感谢

推荐答案

要获得你想要的东西,你需要做一些事情:

To get what you want you will need a few things:

t.forEach(function( aRow ) {
    var newFields = [];
    aRow.fields.forEach( function( aField ){
        var newItems = [];
        aField.items.forEach( function( item ){
            var aNewItem = { item: parseInt(item), ref: 0 };
            newItems.push( aNewItem );
        } );
        newFields.push({ _id: aField._id, items: newItems });
    } )
    aTable.update(
        { _id: aRow._id }, 
        { "$set": { "fields": newFields } }
    );
});

所以基本上你需要在更新之前重构你的数组

So basically you need to "re-construct" your arrays before updating

这篇关于在mongodb shell上更新forEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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