【问题标题】:Mongodb creating alias in a queryMongodb在查询中创建别名
【发布时间】:2011-10-28 22:29:17
【问题描述】:

mongodb 与此查询的等价物是什么:

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

【问题讨论】:

标签: mongodb


【解决方案1】:

可以使用 $project 从另一个字段中创建具有给定名称和值的新字段:

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

以下 $project 阶段添加了新字段 isbn、lastName 和 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

【讨论】:

  • 我接受这个答案是因为项目阶段确实允许字段使用“别名”。有关如何在不修改原始字段值的情况下进行投影的示例,请参见 user1735921 的答案
  • 如果我为“title”创建了一个索引,并且在 $project 中我将“title”更改为“leTitle”,那么排序“leTitle”会使用“title”的索引吗?
【解决方案2】:

您可以使用任何运算符,例如 toUpper 或 toLower 或 concat 或您认为可以使用的任何其他运算符并创建别名。

示例: 在以下示例中,created_time 是集合中的一个字段。 (我不擅长语法,所以你可以纠正它,但这是方法)

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

因此,以这种方式使用运算符,您可以创建任意数量的别名。

【讨论】:

  • 有趣。当被问到这个问题时,我不相信聚合管道已经回来了。我会指出 $concat 可以在不操作值的情况下使用
  • 是的 concat 会更好,无论如何我只是举一个我想到的可能方式的例子......编辑了我的帖子。尽管 Andrey 已经发布了 MongoDB 中已经存在的本机语法。它只是另一种可能的方式,有时在编写复杂查询时会派上用场。
【解决方案3】:

你可以用这个,也许有帮助

数据库数据

{ "_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 命令

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

结果

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

【讨论】:

  • 为我节省了大量研究。谢谢。
猜你喜欢
  • 2014-11-29
  • 2020-05-04
  • 2021-09-14
  • 1970-01-01
  • 2015-04-09
  • 2019-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多