Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb equivalent of SELECT field AS `anothername`

what is the mongodb equivalent of the MySQL query

SELECT username AS  `consname` FROM  `consumer`
like image 212
sajith Avatar asked Nov 13 '13 14:11

sajith


People also ask

What is the equivalent of select in SQL in MongoDB?

An SQL SELECT statement typically retrieves data from tables in a database, much like a mongo shell find statement retrieves documents from a collection in a MongoDB database.

How do I select a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

What is MongoDB alias?

More Detail. In MySQL, we give an alias name for a column. Similarly, you can give an alias name for field name in MongoDB. The MongoDB equivalent syntax is as follows db. yourCollectionName.


1 Answers

As it was mentioned by sammaye, you have to use $project in aggregation framework to rename fields.

So in your case it would be:

db.consumer.aggregate([
    { "$project": {
        "_id": 0,
        "consname": "$username"
    }}
])

Cool thing is that in 2.6.x version aggregate returns a cursor which means it behaves like find.

You might also take a look at $rename operator to permanently change schema.

like image 162
Salvador Dali Avatar answered Oct 04 '22 15:10

Salvador Dali