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

时间:2019-12-18 07:23:27

标签: mongodb

数据迁移。我需要根据条件将“ ActionType”字段从根文档移动到子文档。

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

我需要从下面的结构更改

{
    "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"                   
                }
            ]
        }
    ]
}

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

1 个答案:

答案 0 :(得分:0)

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

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});
相关问题