user2175783
user2175783

Reputation: 1441

Doing a sum with mongo db aggregation framework

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 
}

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

I would like then to sort these sums.

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.

Upvotes: 0

Views: 105

Answers (2)

rsmorros
rsmorros

Reputation: 196

If I understood you correctly:

db.col.aggregate
(
  [{
    $match:
    {
      type1: {$in: ["type1A", type1B",...]},
      type2: {$in: ["type2A", type2B",...]},
      "date.year": 2015,
      "date.month": 4,,
      "date.day": {$gte: 4, $lte: 7},
      "date.type": "day" 
    }
  },
  {
    $group:
    {
       _id: "$iddoc",
       total_count: {$sum: "$count"}
    }  
  },
  { $sort: {total_count: 1}}]
)

This is filtering the field date.day between 4 and 7 inclusive (if not, use $gt and $lt to exclude them). And it sorts results from lower to higher (ascending), if you want to do a descending sort, then:

{ $sort: {total_count: -1}}

Upvotes: 1

JohnnyHK
JohnnyHK

Reputation: 312149

This is straightforward to do with an aggregation pipeline:

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}}
])

Upvotes: 2

Related Questions