将数组的元素转换为MongoDB中的字段

时间:2017-06-14 15:57:14

标签: mongodb

MongoDB中当前存在的数据在字符串数组中包含一堆属性,如下所示:

{ 
    ...,
    "person" : [
        ["John","Doe","22"],
        ["Jane","Doe","24"],
        ...
    ] 
}

阵列都是类似的结构,所以我想知道是否 可以将数组中的元素转换为字段吗? 我的目标是创建一个新的集合,其数据如下所示:

{ 
    ...,
    "person" : [
        {firstname:"John", lastname:"Doe", age:"22"},
        {firstname:"Jane", lastname:"Doe", age:"24"}
        ...
    ] 
}   

我试图用$ project聚合它,但没有成功..
有可能吗?

1 个答案:

答案 0 :(得分:0)

您可以使用聚合将数据转换为所需格式,并将该输出写入新集合。

//To convert data
{ 
    "person" : [
        ["John","Doe","22"],
        ["Jane","Doe","24"]
    ] 
}

//Aggregation to convert data to required format and write to new collection 'new_person'
db.persons.aggregate([
    {
        $unwind:"$person"
    },
    {
        $project: {
            firstName: { $arrayElemAt: [ "$person", 0 ] },
            lastName: { $arrayElemAt: [ "$person", 1 ] },
            age: { $arrayElemAt: [ "$person", 2 ] },
        }
    },
    {
        $group: {
            _id: "$_id",
            person : {$push: {firstName:"$firstName",lastName:"$lastName", age:"$age"}}
        }
    },
    {$out: "new_person"}
])

//Output:
{
    "_id" : ObjectId("594165e85bf0bf7801d042a7"),
    "person" : [
        {
            "firstName" : "John",
            "lastName" : "Doe",
            "age" : "22"
        },
        {
            "firstName" : "Jane",
            "lastName" : "Doe",
            "age" : "24"
        }
    ]
}