MongoDB Aggregation Query- Rename Fields Returned from Within Embedded Documents

前端 未结 2 1966
闹比i
闹比i 2021-01-13 21:04

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 fie

2条回答
  •  有刺的猬
    2021-01-13 21:26

    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"
                    }
                }
            }
        }}
    ])
    

    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.

提交回复
热议问题