如何在mongo DB聚合查询中查询更多字段?
How to query more fields on mongo DB aggregation query?
我想知道如何在 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 } },
])
提前致谢
在 $group 阶段使用运算符 $first (aggregation accumulator)。
例如:
"user_name": {"$first": "$user_name"}
或者对于您正在使用的编程语言(不确定它是什么),尝试类似的东西:
"user_name" => {"$first" => "$user_name"},
例如,请参阅我的 Practical MongoDB Aggregations book
中的“分组和总计”一章
我想知道如何在 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 } },
])
提前致谢
在 $group 阶段使用运算符 $first (aggregation accumulator)。
例如:
"user_name": {"$first": "$user_name"}
或者对于您正在使用的编程语言(不确定它是什么),尝试类似的东西:
"user_name" => {"$first" => "$user_name"},
例如,请参阅我的 Practical MongoDB Aggregations book
中的“分组和总计”一章