本文介绍了MongoDB聚合查询-重命名嵌入式文档中返回的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在使用聚合运算符来返回具有嵌入式(子)文档数组的文档.我想重命名数组的字段名称,还要重命名数组的嵌入式文档中的字段名称.

I'm currently using aggregate operator to return documents that has an array of embedded (sub) documents. I want to rename the field name for the array and also rename fields names in the embedded documents of the array.

作为示例,对于投影,我想将数组从"friends"重命名为"buddies",并且我还想将嵌入式文档中的字段从"name"重命名为"nickName".我可以在聚合操作中执行此操作吗?

As an example, for projection I want to rename the array from "friends" to "buddies" and I also want to rename fields in the embedded document from "name" to "nickName". Can I do this within an aggregate operation and if so how?

这是源文档的示例:

[
    {
        _id: ObjectID,
        name: 'Matthew',
        friends: [
            {name: 'Slim', age: '32'},
            {name: 'buba', age: '36'}
        ]
    }
]

结果如下所示:

[
    {
        _id: ObjectID,
        name: 'Matthew',
        buddies: [
            {nickName: 'Chris', age: '32'},
            {nickName: 'Jim', age: '36'}
        ]
    }
]

非常感谢您的帮助.

推荐答案

有两种方法,但这很大程度上取决于您的MongoDB版本. 2.6及更高版本的最新版本支持 $map > 运算符,您可以在 $project 做你想做的事情:

There are a couple of approaches to this, but it largely depends on your MongoDB version. More recent versions from 2.6 and upwards support the $map operator which you can use in $project to do what you want:

db.friend.aggregate([
    { "$project": {
        "name": 1,
        "buddies": {
            "$map": {
                "input": "$friends",
                "as": "el",
                "in": {
                    "nickName": "$$el.name",
                    "age": "$$el.age"
                }
            }
        }
    }}
])

在以前的版本中,您将使用 $unwind > 处理数组元素并通过 重新构建> $group :

In prior versions you would use $unwind to work with the array elements and re-construct via $group:

db.collection.aggregate([
    { "$unwind": "$friends" },
    { "$group": {
        "_id": "$_id",
        "name": { "$first": "$name" },
        "buddies": {
            "$push": {
                "nickName": "$friends.name",
                "age": "$friends.age"
            }
        }
    }}
])

第一种形式的效率更高,因为您不会对数组内容进行非规范化,也不会在要处理的管道中生成更多文档.

With the first form being a little more efficient as you are not de-normalizing the array content and producing more documents in the pipeline to process.

这篇关于MongoDB聚合查询-重命名嵌入式文档中返回的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 18:03