【发布时间】:2014-05-04 14:10:45
【问题描述】:
我有一个包含 2 条记录的集合 aTable:
{
"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
]
}
]
}
我想从
更新字段 aTable.fields.itemsitems : [ 11,12 ]
到
items : [
{item: 11, key: 0},
{item:12, key: 0}
]
我使用 forEach 浏览字段但无法保存:
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})
} )
} )
});
【问题讨论】:
-
有什么错误吗?另一种选择是直接在 aRow 对象中进行更改,然后调用 db.aTable.save(aRow)
-
因为aRow.fields是数组,所以aRow.fields中的每个元素都有mutil items。 items 是数组。所以我们不能直接在 aRow 中更新
标签: javascript mongodb mongo-shell