MongoDB 聚合范围 [英] MongoDB aggregation over a range

查看:69
本文介绍了MongoDB 聚合范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的文件:

<预><代码>[{日期:"2014-07-07",价值:20},{日期:2014-07-08",值:29},{日期:"2014-07-09",值:24},{日期:2014-07-10",值:21}]

我想运行一个聚合查询,为我提供日期范围内的结果.例如

<预><代码>[{总和:49},{总和:45},]

所以这些是每日值,我需要知道过去 7 天的值字段总和.以及在这些之前的 7 天.例如从 5 月 1 日到 5 月 6 日的总和,然后从 5 月 7 日到 5 月 14 日的总和.

我可以使用多个组和范围的聚合在单个 mongodb 查询中获得此结果吗?

解决方案

您可以使用聚合对可以从源文档计算出的任何内容进行分组,只要您确切地知道要做什么.

根据您的文档内容和示例输出,我猜您是以两天为间隔求和的.以下是编写聚合以将其输出到示例数据上的方法:

var range1={$and:[{"$gte":["$date","2014-07-07"]},{$lte:["$date","2014-07-08"]}]}var range2={$and:[{"$gte":["$date","2014-07-09"]},{$lte:["$date","2014-07-10"]}]}db.range.aggregate({$项目:{dateRange:{$cond:{if:range1, then:"dateRange1",else:{$cond:{if:range2, then:"dateRange2", else:"NotInRange"}}}},值:1}},{$group:{_id:"$dateRange", sum:{$sum:"$value"}}}){_id":dateRange2",总和":45}{_id":dateRange1",sum":49}

将日期替换为 range1 和 range2 中的字符串,并且您可以选择在开始仅对已经在您聚合的完整范围内的文档进行操作之前进行过滤.

I have documents of the following format:

[
  {
    date:"2014-07-07",
    value: 20
  },
  {
    date:"2014-07-08",
    value: 29
  },
  {
    date:"2014-07-09",
    value: 24
  },
  {
    date:"2014-07-10",
    value: 21
  }
]

I want to run an aggregation query that gives me results in date ranges. for example

[
  { sum: 49 },
  { sum:45 },
]

So these are daily values, I need to know the sum of value field for last 7 days. and 7 days before these. for example sum from May 1 to May 6 and then sum from May 7 to May 14.

Can I use aggregation with multiple groups and range to get this result in a single mongodb query?

解决方案

You can use aggregation to group by anything that can be computed from the source documents, as long as you know exactly what you want to do.

Based on your document content and sample output, I'm guessing that you are summing by two day intervals. Here is how you would write aggregation to output this on your sample data:

var range1={$and:[{"$gte":["$date","2014-07-07"]},{$lte:["$date","2014-07-08"]}]}
var range2={$and:[{"$gte":["$date","2014-07-09"]},{$lte:["$date","2014-07-10"]}]}
db.range.aggregate(
    {$project:{
         dateRange:{$cond:{if:range1, then:"dateRange1",else:{$cond:{if:range2, then:"dateRange2", else:"NotInRange"}}}},
         value:1}
    }, 
    {$group:{_id:"$dateRange", sum:{$sum:"$value"}}}
)
{ "_id" : "dateRange2", "sum" : 45 }
{ "_id" : "dateRange1", "sum" : 49 }

Substitute your dates for strings in range1 and range2 and optionally you can filter before you start to only operate on documents which are already in the full ranges you are aggregating over.

这篇关于MongoDB 聚合范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆