我正在尝试更新mongoDB中的集合。结构是这样的:
obj_100
{
id: 123,
name: test_1,
type : [{
name: test_1,
version : 34,
}
{
name: test_65,
version : 344,
}]
}
obj_101
{
id: 124,
name: test_2,
type: [{
name: test_2,
version: 3,
}
{
name: test_25,
version: 323,
}]
}
....
....
现在,我想替换字符串" test"在name
中(无论它在哪里 - 在这种情况下,它位于所有馆藏中的{obj {name}}
和{obj {type {name}}
下),以及"制作"以便它看起来像等,
obj_100
{
id: 123,
name: production_1,
type : [{
name: production_1,
version : 34,
}
{
name: production_65,
version : 344,
}]
}
obj_101
{
id: 124,
name: production_2,
type: [{
name: production_2,
version: 3,
}
{
name: production_25,
version: 323,
}]
}
....
....
我试过了,
$ MONGO_ROOT / bin / mongo 127.0.0.1:27017/cyclops --eval' db.stages.find()。forEach(function(doc){doc.name = doc.name.replace(/ msmaster2int) /," test"); db.stages.save(doc);});'
以上只是更改" name"。同样,我也希望更新数组中的数据。
任何人都可以帮助我吗
答案 0 :(得分:0)
您应该在更新中使用multi :true
,如下所示:
db.stages.update({"name":/test/,"type.name":/test/},{"$set":{"name":"production","type.name":"production"}},false,true )
此处我将name:test
更新为name:production
,首先使用正则表达式搜索name:test
并使用新字符串替换它。但在查看您编辑的问题和预期输出后,我认为您应该使用以下脚本
var bulk = db.collectionName.initializeOrderedBulkOp();
var counter = 0;
db.collectionName.find().forEach(function(data) {
var objectName = data.name; // first get name from outside object
var regex = /(test_)(\d)/;
objectName = objectName.replace(regex, "production_$2"); //replace name to production
for(var ii = 0; ii < data.type.length; ii++) { //iterate over type arry
var typeName = data.type[ii].name; // find type array name
var regex = /(test_)(\d)/;
typeName = typeName.replace(regex, "production_$2"); //replace same here
var typeKey = "type." + ii + ".name";
var updoc = {
"$set": {}
};
updoc["$set"]["name"] = objectName; // set both name and type.name
updoc["$set"][typeKey] = typeName;
bulk.find({
"_id": data._id
}).update(updoc);
counter++;
if(counter % 1000 == 0) {
bulk.execute(); //execute bulk update here
bulk = db.collectionName.initializeOrderedBulkOp();
}
}
})
if(counter % 1000 != 0) bulk.execute();