Is it possible rename fields in the outputs of a M

2019-01-18 22:35发布

问题:

I have some documents in Mongo:

{"name" : "John", "age" : 26}
{"name" : "Paul", "age" : 34}
{"name" : "George", "age" : 36}

and another function that expects documents of the form:

{"name" : "XXX", "value" : YY}

Is it possible to rename the 'age' field to 'value' in a find query in PyMongo?

回答1:

I'd use the aggregate method with $project operator.

From mongodb web docs.

You may also use $project to rename fields. Consider the following example:

db.article.aggregate(
 { $project : {
     title : 1 ,
     page_views : "$pageViews" ,
     bar : "$other.foo"
 }} );`

e.g.

db.mycol.aggregate({ $project : { name:1, value:"$age" }});

see http://docs.mongodb.org/manual/reference/aggregation/#_S_project