4

类似于这个问题

Barrowing 数据集,我有类似的东西:

{
    'user_id':'{1231mjnD-32JIjn-3213}',
    'name':'John',
    'campaigns':
        [
            {
                'campaign_id':3221,
                'start_date':'12-01-2012',
            },
            {
                'campaign_id':3222,
                'start_date':'13-01-2012',
            }
        ]
}

我想像这样添加一个新密钥campaigns

{
    'user_id':'{1231mjnD-32JIjn-3213}',
    'name':'John',
    'campaigns':
        [
            {
                'campaign_id':3221,
                'start_date':'12-01-2012',
                'worker_id': '00000'
            },
            {
                'campaign_id':3222,
                'start_date':'13-01-2012',
                'worker_id': '00000'
            }
        ]
}

如何将insert/update新键放入对象数组?
我想在数组中的每个对象中添加一个新键,默认值为00000.

我努力了:
db.test.update({}, {$set: {'campaigns.worker_id': 00000}}, true, true)
db.test.update({}, {$set: {campaigns: {worker_id': 00000}}}, true, true)

有什么建议么?

4

2 回答 2

2

我假设这个操作会发生一次,所以你可以使用脚本来处理它:

var docs = db.test.find();
for(var i in docs) {
    var document = docs[i];

    for(var j in document.campaigns) {
        var campaign = document.campaigns[j];
        campaign.worker_id = '00000';
    }

    db.test.save(document);
}

该脚本将遍历集合中的所有文档,然后遍历每个文档中的所有活动,设置 *worker_id* 属性。最后,每个文档都被持久化。

于 2012-12-21T10:48:34.933 回答
1
db.test.update({}, {$set: {'campaigns.0.worker_id': 00000}}, true, true

这将更新 0 元素。

如果你愿意,add a new key into every object inside the array你应该使用: $unwind

例子:

{
  title : "this is my title" ,
  author : "bob" ,
  posted : new Date() ,
  pageViews : 5 ,
  tags : [ "fun" , "good" , "fun" ] ,
  comments : [
      { author :"joe" , text : "this is cool" } ,
      { author :"sam" , text : "this is bad" }
  ],
  other : { foo : 5 }
}

展开标签

db.article.aggregate(
    { $project : {
        author : 1 ,
        title : 1 ,
        tags : 1
    }},
    { $unwind : "$tags" }
);

结果:

{
     "result" : [
             {
                     "_id" : ObjectId("4e6e4ef557b77501a49233f6"),
                     "title" : "this is my title",
                     "author" : "bob",
                     "tags" : "fun"
             },
             {
                     "_id" : ObjectId("4e6e4ef557b77501a49233f6"),
                     "title" : "this is my title",
                     "author" : "bob",
                     "tags" : "good"
             },
             {
                     "_id" : ObjectId("4e6e4ef557b77501a49233f6"),
                     "title" : "this is my title",
                     "author" : "bob",
                     "tags" : "fun"
             }
     ],
     "OK" : 1
}

在您可以编写简单的更新查询之后。

于 2012-12-21T09:13:49.650 回答