What is the mongodb's equivalent to this query:
SELECT "foo" as bar,
id
as "spec" from tablename
In MongoDB, since the database is schemaless and the field names are included for every document in the JSON, much more storage space is required than traditional databases with schemas. Because of this, a common practice is to store very short field names in the documents to conserve space.
To access the value of the variable, prefix the variable name with double dollar signs ( $$ ); i.e. "$$<variable>" . If the variable references an object, to access a specific field in the object, use the dot notation; i.e. "$$<variable>. <field>" .
To assign a variable, specify a string for the variable name and assign a valid expression for the value. The variable assignments have no meaning outside the in expression, not even within the vars block itself.
The $project function in MongoDB passes along the documents with only the specified fields to the next stage in the pipeline. This may be the existing fields from the input documents or newly computed fields. Syntax: { $project: { <specifications> } }
It is possible to create new field with given name and value taken from another field with $project:
{
"_id" : 1,
title: "abc123",
isbn: "0001122223334",
author: { last: "zzz", first: "aaa" },
copies: 5
}
The following $project stage adds the new fields isbn, lastName, and copiesSold:
db.books.aggregate(
[
{
$project: {
title: 1,
isbn: {
prefix: { $substr: [ "$isbn", 0, 3 ] },
group: { $substr: [ "$isbn", 3, 2 ] },
publisher: { $substr: [ "$isbn", 5, 4 ] },
title: { $substr: [ "$isbn", 9, 3 ] },
checkDigit: { $substr: [ "$isbn", 12, 1] }
},
lastName: "$author.last",
copiesSold: "$copies"
}
}
]
)
http://docs.mongodb.org/manual/reference/operator/aggregation/project/#pipe._S_project
You can use any operator like toUpper or toLower or concat or any other operator you feel like which you think you can work on and create an alias.
Example: In the following example created_time is a field in the collection. (I am not good with syntax so you can correct it, but this is the approach)
{$project {
"ALIAS_one" : {"$concat" : "$created_time"},
"ALIAS_two" : {"$concat" : "$created_time"},
"ALIAS_three" : {"$concat" : "$created_time"}
}}
So using an operator in that fashion you can create as many as aliases as your like.
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