Mongo $ addField用于嵌套结构化数据

时间:2018-12-18 10:17:14

标签: mongodb mongoose mongodb-query aggregation-framework

我得到如下所示的结果,是否有任何办法可以更改_id的值,该值对于所有嵌套数据都相同。我想使用其他名称重命名每个ID,而不仅仅是_id

{
     "items": [
                {
                    "_id": "5bd1a3da2901d60f9edc4d10",
                    "addons": [
                        {
                            "_id": "5bd1a3da2901d60f9edc4d96",
                            "options": [
                                {
                                    "_id": "5bd1a3da2901d60f9edc4d98",
                                }
                            ],
                        }
                    ]
                }
            ] 
    }

在上面的代码中,我尝试了$addfields属性,但是它仅适用于最顶层的嵌套 这是我尝试过的代码:

Items.aggregate([
            { 
                $match: {  _id: '123'}
            },      
            { $addFields: { item_id: "$_id" , 
                            "addons.addon_id" :  "$addons._id" , 
                   "addons.options.options_id" : "$addons.options._id" 
                 } 
             },
            {
                $project: {
                    _id: 0
                }
            },
        ],

此代码工作正常,并在根元素中添加了item_id,但将addon和option_id添加为数组值,

{
    "item_list": [
        {
            "_id": "5bd1a3da2901d60f9edc4d10",
            "addons": [
                {
                    "_id": "5bd1a44b2901d60f9edc4d9a",
                    "options": [
                        {
                            "_id": "5bd1a44b2901d60f9edc4d9b",
                            "options_id": [
                                [
                                    "5bd1a44b2901d60f9edc4d9b"
                                ]
                            ]
                        }
                    ],
                    "addon_id": [
                        "5bd1a44b2901d60f9edc4d9a"
                    ]
                }
            ]
        }
    ]
}

我得到了类似这样的嵌套数组,即addon_id和options_id的嵌套数组,我希望它是一个简单的字符串而不是数组,

{
    "item_list": [
        {
            "_id": "5bd1a3da2901d60f9edc4d10",
            "addons": [
                {
                    "_id": "5bd1a44b2901d60f9edc4d9a",
                    "options": [
                        {
                            "_id": "5bd1a44b2901d60f9edc4d9b",
                            "options_id": "5bd1a44b2901d60f9edc4d9b"
                        }
                    ],
                    "addon_id": "5bd1a44b2901d60f9edc4d9a"
                }
            ]
        }
    ]
}

我期望以上结果。

0 个答案:

没有答案