用mongo db聚合框架求和 [英] Doing a sum with mongo db aggregation framework

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

问题描述

我在mongo db的集合中有以下类型的文档

I have the following kind of docs in a collection in mongo db

{   _id:xx, 
    iddoc:yy,   
    type1:"sometype1", 
    type2:"sometype2",
    date: 
    { 
      year:2015,
      month:4,
      day:29,
      type:"day"
    },
    count:23 
}

我想对所有文档的iddoc分组字段总计:

I would like to do a sum over the field count grouping by iddoc for all docs where:


  • [ type1A, type1B,...]中的type1

  • 其中,[[type2A, type2B中的type2 ...]

  • date.year:2015年,

  • date.month:4,

  • date .type: day

  • date.day 4到7之间

  • type1 in ["type1A","type1B",...]
  • where type2 in ["type2A","type2B",...]
  • date.year: 2015,
  • date.month: 4,
  • date.type: "day"
  • date.day between 4 and 7

我想要然后将这些总和排序。

I would like then to sort these sums.

我认为在mongo db聚合框架内这可能很容易做到,但我是新手,不胜感激。 / p>

I think this is probably easy to do within mongo db aggregation framework but I am new to it and would appreciate a tip to get started.

推荐答案

Th使用聚合管道

db.test.aggregate([
  // Filter the docs based on your criteria
  {$match: {
    type1: {$in: ['type1A', 'type1B']},
    type2: {$in: ['type2A', 'type2B']},
    'date.year': 2015,
    'date.month': 4,
    'date.type': 'day',
    'date.day': {$gte: 4, $lte: 7}
  }},

  // Group by iddoc and count them
  {$group: {
    _id: '$iddoc',
    sum: {$sum: 1}
  }},

  // Sort by sum, descending
  {$sort: {sum: -1}}
])

这篇关于用mongo db聚合框架求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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