如何将Mongodb文档中的数组转换为JsonArray?

问题描述 投票:1回答:1

我试图将 "interesse "数组转换为一个新的对象,其中有2个字段 "term",即当前数组中的条款和一个统计值,名称为 "str",起始值为0,如下例所示.我的数据库目前有大约16KK的条目,所以我试图创建某种函数或例程来处理它。

原始文件

{
    "email" : "[email protected]",
    "interesse" : [ 
        "Calcados", 
        "Acessorios para viagem", 
        "Interesse em noticias sobre curiosidades"
    ],
    "data" : "2017-01-30"
}

{
    "email" : "[email protected]",
    "interesse" : [ 
        "Eletrodomesticos e portateis", 
        "Geladeiras"
    ],
    "data" : "2017-01-30"
}

结果文件

{
    "email" : "[email protected]",
    "interesse" : [ 
        {"term":"Calcados","str":0}, 
        {"term":"Acessorios para viagem","str":0},
        {"term":"Interesse em noticias sobre curiosidades","str":0}
    ],
    "data" : "2017-01-30"
}

{
    "email" : "[email protected]",
    "interesse" : [ 
        {"term":"Eletrodomesticos e portateis","str":0}, 
        {"term":"Geladeiras","str":0},
    ],
    "data" : "2017-01-30"
}

我在看arrayToObject...但这个函数只能将整个数组转换为一个对象...我想要的是将每个值转换为新的对象...。

arrays json mongodb
1个回答
2
投票

你需要 $addFields 替换现有的外地和 $map 来转换你当前的数组。

db.collection.aggregate([
    {
        $addFields: {
            interesse: {
                $map: {
                    input: "$interesse",
                    in: {
                        term: "$$this", str: 0
                    }
                }
            }
        }
    }
])

Mongo Playground

© www.soinside.com 2019 - 2024. All rights reserved.