首页 > 解决方案 > 项目值作为键,嵌入文档作为 mongo 中的值

问题描述

在 mongodb 我有一个结构文件:

{
    "phone":"123",
    "friends": {
                    "contacts":{
                                    "234":2,
                                    "345":5
                               }
               }
}

我希望输出看起来像:

{
    "123": {
                "234":2,
                "345":5
           }
}

我已经搜索了多种解决方案。似乎没有得到解决方案。

标签: mongodb

解决方案


您可以使用$arrayToObject创建自定义键(将一k-v对数组作为参数),然后您可以使用$replaceRoot获取自定义根对象,尝试:

db.collection.aggregate([
    {
        $match: {
            phone: { $exists: true },
            "friends.contacts": { $exists: true }
        }
    },
    {
        $addFields: {
            array: [{
                k: "$phone",
                v: "$friends.contacts"
            }]
        }
    },
    {
        $replaceRoot: {
            newRoot: { $arrayToObject: "$array" }
        }
    }
])

推荐阅读