Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use alias name in find query in MongoDB

Tags:

mongodb

How can we use an alias name in find method of mongodb as we do in mySQL like:

select user_id as id from users

Please provide some help, thank you!

like image 830
Mukesh Rawat Avatar asked Oct 18 '16 12:10

Mukesh Rawat


2 Answers

Please refer to Aggregation pipeline : Project

Following query should do the job :

db.users.aggregate([{$project:{id:"$user_id"}}])
like image 165
inaitgaJ Avatar answered Oct 10 '22 06:10

inaitgaJ


You can use mongodb aggregate method with pipeline stages to get the desired result: list of stages

eg. :

db.[collection].aggregate(pipeline)

Pipeline contains different stages:

pipeline = [{match, projection, ...}]

There are other parts also in stages, please refer to the link mentioned above.

In your case i can write below query:

db.users.aggregate([{$match:{"_id":"<some_value>"}},{$project:{id:"$user_id", default_key:"default_value", "excluded_key": 0, "included_key": 1}}])

$match:{"_id":""}} -> This is matching query , its output will be executed in next stage. eg. $projection in our case.

id:"$user_id" -> in this case we are giving id as alias name to user_id key in mongo-db collection.

default_key:"default_value" -> in this case default_key field will be added in the response with default value mentioned in place of "default_value".

"excluded_key": 0 -> in this case excluded_key will be removed from the response.

"included_key": 1 -> in this case included_key will be part of the response.

like image 3
Raghav salotra Avatar answered Oct 10 '22 07:10

Raghav salotra