【问题标题】:How to query more fields on mongo DB aggregation query?如何在mongoDB聚合查询中查询更多字段?
【发布时间】:2021-10-09 01:15:57
【问题描述】:

我想知道如何在collection.aggregate的响应中添加额外的字段?

下面的查询按 user_id 对活动进行分组。而且我想知道如何在响应中包含 user_name。

数据库模型

class Activity
  include Mongoid::Document
  field :hd_race_id, type: Float
  field :metric_elapsed_time, type: Float
  field :metric_distance, type: Float
  field :user_name, type: String
  belongs_to :user
  ...


class User
  include Mongoid::Document
  field :user_name, type: String
  has_many :activities
  ...

查询

Activity.collection.aggregate([          
      {
        "$group" => {
          "_id" => "$user_id",
          "distance" => { "$sum" => "$metric_distance" },
          "time" => { "$sum" => "$metric_elapsed_time" },
        },
      },
      { "$sort" => { "distance" => -1 } },          
    ])

提前谢谢你

【问题讨论】:

    标签: ruby-on-rails ruby mongodb mongoid


    【解决方案1】:

    $group 阶段内使用运算符 $first (aggregation accumulator)

    例如:

    "user_name": {"$first": "$user_name"}
    

    或者对于您正在使用的编程语言(不确定它是什么),请尝试以下操作:

    "user_name" => {"$first" => "$user_name"},
    

    例如,请参阅我的Practical MongoDB Aggregations book 中的“组和总计”一章

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 2020-09-10
      相关资源
      最近更新 更多