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

前端 未结 4 2125
我寻月下人不归
我寻月下人不归 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:31

    As mentioned by @Neil Lunn this can be achieved with an aggregation pipeline:

    And starting Mongo 4.2, the $replaceWith aggregation operator can be used to replace a document by a sub-document:

    // { level1: { level2: { coordinates: [10, 20] }, b: 4 }, a: 3 }
    db.collection.aggregate(
      { $replaceWith: { coords: "$level1.level2.coordinates" } }
    )
    // { "coords" : [ 10, 20 ] }
    

    Since you mention findOne, you can also limit the number of resulting documents to 1 as such:

    db.collection.aggregate([
      { $replaceWith: { coords: "$level1.level2.coordinates" } },
      { $limit: 1 }
    ])
    

    Prior to Mongo 4.2 and starting Mongo 3.4, $replaceRoot can be used in place of $replaceWith:

    db.collection.aggregate(
      { $replaceRoot: { newRoot: { coords: "$level1.level2.coordinates" } } }
    )
    

提交回复
热议问题