【问题标题】:How to execute multiple aggregate in one trip to mongodb?如何在一次mongodb中执行多个聚合?
【发布时间】: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 => Name
where => LastItem._t = Type3
return => 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


【解决方案1】:

MongoDB 3.4 可以使用 $facet 同时处理多个聚合框架管道。

$facet 阶段允许您创建多面聚合,在单个聚合阶段中跨多个维度或多面表征数据。多面聚合提供多个过滤器和分类来指导数据浏览和分析。分面的常见实现是有多少在线零售商提供了通过对产品价格、制造商、尺寸等应用过滤器来缩小搜索结果的方法。 LINK

这不是“任何时候都可以”使用的东西。在我看来,您应该考虑优化您的管道,而不是创建多个耗时的管道。

那么你的问题也可以通过在同一个 $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}}

祝你好运!

【讨论】:

  • 你能告诉我吗!为什么我们不使用多重聚合而不是单一聚合
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-07
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多