在mongoDB中使用新键更新对象数组 [英] Updating an array of objects with a new key in mongoDB
问题描述
类似于此问题
使数据集广为人知,我与此类似:
Barrowing the data set, I have something similar to this:
{
'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
中添加一个新密钥,如下所示:
And I want to add a new key in the campaigns
like so:
{
'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
向数组内的每个对象添加一个新键.
How to insert/update
a new key into an array of objects?
I want to add a new key into every object inside the array with a default value of 00000
.
我尝试过:
db.test.update({}, {$set: {'campaigns.worker_id': 00000}}, true, true)
db.test.update({}, {$set: {campaigns: {worker_id': 00000}}}, true, true)
I have tried:
db.test.update({}, {$set: {'campaigns.worker_id': 00000}}, true, true)
db.test.update({}, {$set: {campaigns: {worker_id': 00000}}}, true, true)
有什么建议吗?
推荐答案
我假设此操作将发生一次,因此您可以使用脚本来处理它:
I'm supposing that this operation will occur once, so you can use a script to handle it:
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 *属性. 最后,每个文档都将保留.
The script will iterate over all documents in your collection then over all campaigns in each document, setting the *worker_id* property. At the end, each document is persisted.
这篇关于在mongoDB中使用新键更新对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!