How do I rename fields when performing search/projection in MongoDB?

前端 未结 4 2106
我寻月下人不归
我寻月下人不归 2020-12-02 20:01

Is it possible to rename the name of fields returned in a find query? I would like to use something like $rename, however I wouldn\'t like to change the documen

4条回答
  •  天命终不由人
    2020-12-02 20:22

    As we know, in general, $project stage takes the field names and specifies 1 or 0/true or false to include the fields in the output or not, we also can specify the value against a field instead of true or false to rename the field. Below is the syntax

        db.test_collection.aggregate([
            {$group: {
                _id: '$field_to_group',
                totalCount: {$sum: 1}
            }},
            {$project: {
                _id: false,
                renamed_field: '$_id',    // here assigning a value instead of 0 or 1 / true or false effectively renames the field.
                totalCount: true
            }}
        ])
    

提交回复
热议问题