简体   繁体   中英

Is it possible rename fields in the outputs of a Mongo query in PyMongo?

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?

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"
 }} );`

eg

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM