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

在MongoDB中将数组元素转换为字段,mongodb,Mongodb,MongoDB中当前存在的数据包含字符串数组中的一组属性,如下所示: { ..., "person" : [ ["John","Doe","22"], ["Jane","Doe","24"], ... ] } 数组的结构都很相似,所以我想知道 可以将数组中的元素转换为字段吗? 我的目标是收集一个新的数据,如下所示: { ..., "person" : [ {firstname:"Joh

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

{ 
    ...,
    "person" : [
        ["John","Doe","22"],
        ["Jane","Doe","24"],
        ...
    ] 
}
数组的结构都很相似,所以我想知道 可以将数组中的元素转换为字段吗?
我的目标是收集一个新的数据,如下所示:

{ 
    ...,
    "person" : [
        {firstname:"John", lastname:"Doe", age:"22"},
        {firstname:"Jane", lastname:"Doe", age:"24"}
        ...
    ] 
}   
我试图将其与$project合并,但没有成功。

是否可能?

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

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