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!
Please refer to Aggregation pipeline : Project
Following query should do the job :
db.users.aggregate([{$project:{id:"$user_id"}}])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With