Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 369
nickponline Avatar asked Jan 22 '13 16:01

nickponline


People also ask

How do I rename a field in MongoDB?

The $rename operator updates the name of a field and has the following form: {$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } } The new field name must differ from the existing field name. To specify a <field> in an embedded document, use dot notation.

How do you rename a collection in MongoDB using Python?

The PyMongo function rename() is used to rename a collection. The rename operation fails if the new name is not an instance of basestring or it is an invalid collection name. Parameters : new_name : The new name of the collection.

What does find_One return PyMongo?

The find_One() method of pymongo is used to retrieve a single document based on your query, in case of no matches this method returns nothing and if you doesn't use any query it returns the first document of the collection.

How do I find the field name in MongoDB?

ASP.NET Core 3 MVC Application with MongoDByourCollectionName. insertOne({“YourFieldName”:yourValue, “yourFieldName”:”yourValue”,....... N}); If you want a single record from a collection, you can use findOne() and in order to get all records from the collection, you can use find().


1 Answers

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

like image 193
sambomartin Avatar answered Sep 18 '22 19:09

sambomartin