MongoDB查询,用于根据条件将字段从根文档移动到子文档



Data Migration.我需要根据条件将"操作类型"字段从根文档移动到子文档。

条件:不为空且至少具有一个文档数组的子文档。

我需要从下面的结构中更改

{
"ItemId" : "ITM-A",
"ActionType" : "Rent"
"BucketInfo" : [ 
{
"BucketType" : "damage",
"BucketDetailInfo" : []
},
{
"BucketType" : "repair",
"BucketDetailInfo" : [ 
{                    
"EntityType" : "service"
},
{                    
"EntityType" : "service"                    
}
]
}, 
{
"BucketType" : "missing",
"BucketDetailInfo" : []
}, 
{
"BucketType" : "broken",
"BucketDetailInfo" : [ 
{                    
"EntityType" : "service"                
}
]
}
]
}

到下面的结构,操作类型要移动到具有文档数组的子文档

{
"ItemId" : "ITM-A", 
"BucketInfo" : [ 
{
"BucketType" : "damage",
"BucketDetailInfo" : []
}, 
{
"BucketType" : "repair",
"BucketDetailInfo" : [ 
{                    
"EntityType" : "service",
"ActionType" : "Rent"                   
},
{                    
"EntityType" : "service",                  
"ActionType" : "Rent"
}
]
}, 
{
"BucketType" : "missing",
"BucketDetailInfo" : []
}, 
{
"BucketType" : "broken",
"BucketDetailInfo" : [ 
{                    
"EntityType" : "service",
"ActionType" : "Rent"                   
}
]
}
]
}

请让我了解如何实现这一目标。

我通过以下查询获得了结果

db.getCollection('Table').find( {},  {'ActionType' : 1}).forEach(function(doc){
db.getCollection('Table').update(
{_id: doc._id},
{ $set: { "BucketInfo.$[].BucketDetailInfo.$[].ActionType" : doc.ActionType } },
{ multi: true}
)
});
db.getCollection('Table').update({}, {$unset: {ActionType:1}} , {multi: true});

最新更新