【问题标题】:MongoDB Query to move field from root document to sub-document based on conditionMongoDB查询根据条件将字段从根文档移动到子文档
【发布时间】:2020-04-10 17:20:55
【问题描述】:

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

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

我需要从下面的结构改变

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

请告诉我如何实现这一点。

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    我通过下面的查询得到了结果

    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});
    

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 2019-07-11
      • 2016-07-25
      • 2018-12-01
      • 1970-01-01
      • 2016-03-12
      相关资源
      最近更新 更多