如何用现有数据更改mongodb的整个架构?

时间:2016-11-07 01:32:19

标签: mongodb

我正在尝试将数据库mysql更改为mongodb, 想要改变整个数据模式。

我成功迁移了数据。

但是我想从

更改这个mongodb文档架构
{
    "_id" : ObjectId("581c45b1a5245ca984000009"),
    "memb_id" : "ME20160520041223736026",
    "story_category_id" : "S001000",
    "story_pet_category" : "D",
    "temp_text" : "THIS IS DATA TO CHANGE",
    "story_status" : "D",
    "regtime" : 1463988822,
    "modifytime" : 1468573528,
    "story_contents" : [ 
        {
            "story_image_url" : "/uploads/2016/05/23/compression/728870e82c47901a70509cfdc2bc3b56.jpg"
        }, 
        {
            "story_image_url" : "/uploads/2016/05/23/compression/fd1552e1ea5380fc0cdae793336a8d67.jpg"
        }, 
        {
            "story_image_url" : "/uploads/2016/05/23/compression/2aaff6a75db4c8bfa1a0133234d3e6fe.jpg"
        }
    ]
}

{
    "_id" : ObjectId("581c45b1a5245ca984000009"),
    "memb_id" : "ME20160520041223736026",
    "story_category_id" : "S001000",
    "story_pet_category" : "D",
    "story_status" : "D",
    "regtime" : 1463988822,
    "modifytime" : 1468573528,
    "story_contents" : [
        {
            "story_text":"THIS IS DATA TO CHANGE",
            "story_image_url":""
        }
        {
            "story_text":"",
            "story_image_url" : "/uploads/2016/05/23/compression/728870e82c47901a70509cfdc2bc3b56.jpg"
        }, 
        {
            "story_text":"",
            "story_image_url" : "/uploads/2016/05/23/compression/fd1552e1ea5380fc0cdae793336a8d67.jpg"
        }, 
        {
            "story_text":"",
            "story_image_url" : "/uploads/2016/05/23/compression/2aaff6a75db4c8bfa1a0133234d3e6fe.jpg"
        }
    ]
}

正是我想要的是在“story_contents”数组中推送“temp_text”,更改“story_contents”这样的架构。 (整个6423文件)

如何编写mongodb查询..?

1 个答案:

答案 0 :(得分:0)

您可以使用aggregation来为story_text数组中的所有项添加story_contents字段/值:

db.collection.aggregate([{
    $unwind: "$story_contents"
}, {
    $group: {
        _id: "$_id",
        memb_id: { $first: "$memb_id" },
        story_category_id: { $first: "$story_category_id" },
        story_pet_category: { $first: "$story_pet_category" },
        story_status: { $first: "$story_status" },
        regtime: { $first: "$regtime" },
        modifytime: { $first: "$modifytime" },
        story_contents: {
            $push: { temp_text: "$temp_text", story_image_url: "$story_contents.story_image_url" }
        }
    }
}, {
    $out: "collection2"
}])
  • 1 $unwindstory_contents数组转换为JSON对象
  • 1 $group重新组合_id之前的所有项目,并构建具有其他story_contents字段的新数组temp_text
  • 1 $out将结果写入名为collection2
  • 的新集合中