Reputation: 3862
Is there are a way to do this is Mongo like in mysql.
Mysql
select name,pass,'20' as age from table
Mongo
Some Query to collection
Document will have
{
name:"name",
pass:"pass",
age:'20'
}
Upvotes: 1
Views: 666
Reputation: 1
You may use aggregate and $project operator to add extra columns in the document. Example below:
db.getCollection('table').aggregate([{ $project{"name":1,"pass":1,"age":"20"}}])
Upvotes: 0
Reputation: 151112
Use .aggregate()
, with $addFields
or $project
and $literal
for the value.
Explicit selection:
db.collection.aggregate([
{ "$project": {
"name": 1,
"pass": 1,
"age": { "$literal": '20' }
}}
])
Or $addFields
to just "append" to the existing fields:
db.collection.aggregate([
{ "$addFields": {
"age": { "$literal": '20' }
}}
])
Actually $literal
is not needed for $addFields
since its implemented as a sort of "merge" anyway and does not have the legacy argument restrictions of $project
. But it does not hurt and makes the difference less confusing.
Only .aggregate()
( or indeed mapReduce
) "atlter" documents to return from their original form. All you can do with .find()
and it's supported "projection" is to "include" or "exclude" properties, or array members since this is document database afterall.
Changing shape generally requires .aggregate()
as your general tool.
The alternate case is of course to add the data "after" you return results from the server. For a constant value this generally makes the most sense and there is another reason to do this as well:
db.collection.find({},{ name: 1, pass: 1 }).map( doc =>
Object.assign(doc,{ age: '20' })
)
That's a pretty simple construct and all drivers have a similar method for cursor transformation.
The main reason you should consider this is because there is little point returning information from the database server that increases the payload of the response when you can just as easily add it in post processing.
This means less traffic from your database server as well, and that's something you really should consider when you pay for this as a service like you commonly do in modern environments.
So under the category of "just because you can does not mean you should", which should also apply to other database engines as well, don't make the database do things you really do not need to.
But really its a personal choice.
Upvotes: 1