Mongodb creates an alias in a request

What is mongodb equivalent to this query:

CHOOSE "foo" as the string, idas "spec" from tablename

+5
source share
3 answers

You can create a new field with the given name and value taken from another field using $ project:

{
  "_id" : 1,
  title: "abc123",
  isbn: "0001122223334",
  author: { last: "zzz", first: "aaa" },
  copies: 5
}

The next stage of $ project adds the new fields isbn, lastName and copySold:

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

+9
source

You can use any operator, for example, toUpper or toLower or concat or any other operator with which you think you can work and create an alias.

: created_time - . ( , , )

{$project {
"ALIAS_one" : {"$concat" : "$created_time"},
"ALIAS_two" : {"$concat" : "$created_time"},
"ALIAS_three" : {"$concat" : "$created_time"}
}}

, , , .

+2

you can use it 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 team

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" }
0
source

All Articles