【发布时间】:2017-07-15 08:27:26
【问题描述】:
我需要在一次 mongodb 中执行多个聚合。 在某些情况下在一个集合上,在另一个集合上。 是否可以? 如果可能,怎么做?
对不起,我的英语不好。
我的收藏是这样的:
{
_id: ....,
Name: "Name1",
LastItem: {
_t: "Type3",
Count: 5,
Date: 2017
},
Items: [{
_t: "Type1",
Count: 1,
Date: 2016
},
{
_t: "Type2",
Count: 0,
Date: 2013
},
{
_t: "Type3",
Count: 5,
Date: 2017
},
{
_t: "Type4",
Count: 2,
Date: 2010
},
]
}{
_id: ....,
Name: "Name2",
LastItem: {
_t: "Type1",
Count: 8,
Date: 2017
},
Items: [{
_t: "Type1",
Count: 8,
Date: 2017
},
{
_t: "Type2",
Count: 10,
Date: 2014
},
{
_t: "Type3",
Count: 50,
Date: 2015
},
{
_t: "Type4",
Count: 12,
Date: 2011
},
]
}{
_id: ....,
Name: "Name3",
LastItem: {
_t: "Type3",
Count: 15,
Date: 2016
},
Items: [{
_t: "Type1",
Count: 11,
Date: 2009
},
{
_t: "Type3",
Count: 15,
Date: 2016
},
]
}
我想在一次访问 mongodb 时执行以下 2 个聚合:
1-groupBy => Name
where => items containe (Type3)return => count(Name)
2-groupBy => Namewhere => LastItem._t = Type3return => count(Name)
【问题讨论】:
-
你没有。最好通过示例数据来描述您实际需要做的事情,因为您的实际问题肯定有解决方案,但您的问题实际上并没有提供足够的信息。提出一个可解决的案例,有人会解决它。
-
您能更好地描述一下“多重聚合”的含义吗?
-
聚合框架可以使用$facet同时执行多个聚合;这是你要找的吗?
-
您的问题可以在单个 Group 操作中解决,如下所示:
-
{$unwind: "$Items"} ,{ $group: { _id: "$Name", Type3_in_Items: {$sum: {$cond: [{$eq: ["$Items. _t", "Type3"]}, 1, 0] }}, Type3_Counts_in_Items: {$sum: {$cond: [{$eq: ["$Items._t", "Type3"]}, "$Items.Count ", 0] }}, Type3_in_LastItem: {$addToSet: {$cond: [{$eq: ["$LastItem._t", "Type3"]}, 1, 0] }} } } ,{$sort: { “_id”:1}}
标签: c# mongodb aggregation-framework