2016-12-02 61 views
0

的MongoDB:一个属性添加到指定的用户集合的子文档

db.users.insertMany(
[ 
{ 
    _id: 1, 
    name: "sue", 
    points: [ 
     { points: 85, bonus: 20 }, 
     { points: 85, bonus: 10 } 
    ] 
}, 
{ 
    _id: 2, 
    name: "bob", 
    points: [ 
     { points: 85, bonus: 20 }, 
     { points: 64, bonus: 12 } 
    ] 
}]); 

如何添加属性bonus_rawpoints,与bonus值的值的副本?我想:

db.getCollection('users').update({ }, 
    {$set:{ 'points.$.bonus_raw' : 'points.$.bonus' }}, false, true) 

,但我得到:

的位置经营者没有找到查询所需的匹配。未知的更新:points。$。bonus_raw

回答

1

从目前在MongoDB中更新数组中的多个项目是不可能的。

为了做到这一点,您将不得不查询文档,遍历所有嵌套文档,然后将其保存回MongoDB。

在你的情况,这可以帮助: -

db.users.find({points: { $exists: true } }).forEach(function (doc){ 
    doc.points.forEach(function (points) { 
     points.bonus_raw = points.bonus; 
    }); 
    db.users.save(doc) 
}); 

而且,照顾的竞争条件,在做这样的更新。 See this

相关问题