在mongo id中选择*

时间:2016-09-02 07:23:22

标签: ruby-on-rails mongoid

我收到了这个问题:

User.collection.aggregate([
      {"$project" => {
        "dayOfMonth" => {"$dayOfMonth" => "$created_time"},
        "month" => {"$month" => "$created_time"},
        "year" => {"$year" => "$created_time"},
      }},
      {"$group" => {
        "_id" => { "dayOfMonth" => "$dayOfMonth", "month" => "$month", "year" => "$year"},
        "Total" => {"$sum" => 1}
      }},
      {"$sort" => {
        "created_at" => -1
      }}
    ])

我的用户表包含我需要的用户名和全名,

我做了类似

的事情
User.collection.aggregate([
          {"$project" => {
            "dayOfMonth" => {"$dayOfMonth" => "$created_at"},
            "month" => {"$month" => "$created_at"},
            "year" => {"$year" => "$created_at"},
            "username" => "$username"
          }},
          {"$group" => {
            "_id" => { "dayOfMonth" => "$dayOfMonth", "month" => "$month", "year" => "$year"},
            "Total" => {"$sum" => 1}
          }},
          {"$sort" => {
            "created_at" => -1
          }}
        ])

但它不起作用,并给出与上面相同的结果,不打印用户名,任何想法? 我的目标是在按日期创建分组后获取用户名。

1 个答案:

答案 0 :(得分:0)

我觉得这个问题很愚蠢,那个时候mongo db是全新的。现在我非常擅长经验,并想回答我提出的愚蠢问题。

User.collection.aggregate([
          {"$project" => {
            "dayOfMonth" => {"$dayOfMonth" => "$created_at"},
            "month" => {"$month" => "$created_at"},
            "year" => {"$year" => "$created_at"},
            "username" => "$username"
          }},
          {"$group" => {
            "_id" => { "dayOfMonth" => "$dayOfMonth", "month" => "$month", "year" => "$year"},
            "Total" => {"$sum" => 1},
            "username" => {"$first" => "$username"}
          }},
          {"$sort" => {
            "created_at" => -1
          }}
        ])