【问题标题】:Dictionary to Array of Objects字典到对象数组
【发布时间】:2020-12-06 10:28:13
【问题描述】:

我的数据中有一个字典字段,如下所示:

"details": {
        "code": "PPIO",
        "product": [{
            "productCode": "ADGT"
        }]
    }

我需要将字段转换为对象数组:

"details":
        [
        {
        "code": "PPIO",
        "product": [{
            "productCode": "ADGT"
        }]
        }
        ]

【问题讨论】:

    标签: arrays json mongodb mongodb-query nosql


    【解决方案1】:

    您可以使用$addFields 覆盖现有字段:

    db.collection.aggregate([
        {
            $addFields: {
                details: [ "$details" ]
            }
        }
    ])
    

    Mongo Playground

    编辑:

    对于更新,您可以使用下面的syntax

    db.col.updateMany({}, [{ $set: { details: [ "$details" ] } }])
    

    编辑 2: 或者,如果 updateMany 不适合您,您可以使用 $out 运算符,它将您的集合完全替换为聚合结果:

    db.collection.aggregate([
        {
            $addFields: {
                details: [ "$details" ]
            }
        },
        { $out: "collection" }
    ])
    

    【讨论】:

    • 我应该如何更新收藏?
    • db.col.updateMany({}, [{ $set: { details: [ "$details" ] } }]) 这不起作用。返回以下内容:"details" : [ "$details" ],
    • @balkotdude 你的 MongoDB 版本是多少?
    • MongoDB shell 版本 v4.2.3
    • @balkotdude 这个 $set 是 4.2(服务器版本)中引入的新功能。您可以使用$out(见我修改后的答案)作为备份
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 2011-11-17
    相关资源
    最近更新 更多