mar*_*ers 5 javascript mongodb mongo-shell
我有一个具有以下结构的mongodb文档
> db.user.find().limit(1);
{ "_id" : "1", "foo" : { "bars" : [
{
"name" : "bar1"
},
{
"name" : "bar2"
},
], ... }, ... }
Run Code Online (Sandbox Code Playgroud)
我想为每个人添加一个新属性bar.我已经让我的脚本迭代了bars数组,但我无法在那里获得新属性,我该怎么做?
var users = db.user.find({"foo.bars":{$exists:true}});
users.forEach(function(user) {
user.foo.bars.forEach(function(bar)
{
printjson(bar);
//how can I specify the current 'bar' in this update?
//db.experience.update({_id: user._id}, {$set: {"what goes here?" : "newbarValue"}});
});
});
Run Code Online (Sandbox Code Playgroud)
stu*_*ing 10
传道人说:
var users = db.user.find({"foo.bars":{$exists:true}});
users.forEach(function(user) {
var id = user._id;
var foo_bars = user.foo.bars;
var new_foo_bars = [];
for(var i = 0; i < foo_bars.length; i++) {
var foo_bar = foo_bars[i];
foo_bar['newkey'] = 'newvalue';
new_foo_bars.push(foo_bar);
}
db.user.update({"_id":id}, {$set:{"foo.bars":new_foo_bars}});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5105 次 |
| 最近记录: |