Fatmuemoo
Fatmuemoo

Reputation: 2217

Mongodb creating alias in a query

What is the mongodb's equivalent to this query:

SELECT "foo" as bar, id as "spec" from tablename

Upvotes: 16

Views: 49307

Answers (3)

Edward
Edward

Reputation: 1319

you can use this, maybe help

database data

{ "_id" : "5ab0f445edf197158835be63", "userid" : "5aaf15c28264ee17fe869ad8", "lastmodified" : ISODate("2018-03-21T07:04:41.735Z") }
{ "_id" : "5ab0f445edf197158835be64", "userid" : "5aaf15c28264ee17fe869ad8", "lastmodified" : ISODate("2018-02-20T12:31:08.896Z") }
{ "_id" : "5ab0f445edf197158835be65", "userid" : "5aaf15c28264ee17fe869ad7", "lastmodified" : ISODate("2018-02-20T02:31:08.896Z") }

mongo command

db.zhb_test.aggregate(
[{
    $group: {
        _id: {
            $dateToString: {
                format: "%Y-%m",
                date: "$lastmodified"
            }
        },
        count: {
            $sum: 1
        }
    }
},
{
    $project: {
        "month": "$_id",
        count: 1,
        "_id": 0
    }
}])

result

{ "count" : 2, "month" : "2018-02" }
{ "count" : 1, "month" : "2018-03" }

Upvotes: 3

user1735921
user1735921

Reputation: 1389

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.

Upvotes: 5

Andrey Dolgikh
Andrey Dolgikh

Reputation: 931

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

Upvotes: 23

Related Questions