Keeping field in mongodb group by

淺唱寂寞╮ 提交于 2021-02-08 11:14:06

问题


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:

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.

I know now how to do this (see this question)

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

but would like some of the fields in the match operation to appear in the final document. Is this possible? How?


回答1:


I believe that this query is a solution for what you are asking:

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 type1 and count them
  {$group: {
    _id: { iddoc: '$iddoc', type1: '$type1' },
    sum: {$sum: 1},
    type2: { $push: '$type2' },
    year: { $first: '$date.year' },
    month: { $first: '$date.month' },
    day: { $addToSet: '$date.day' }
  }},

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

There are some options with how you want to see the rest of the fields. I chose to push the type2 to an array (allowing for duplicates), take the first value for year and month since those will always be 2015 and 4 per your match operation, and addToSet the day to an array (not allowing for duplicates). Another option would be to push the entire document into an array of matches, but one should be careful with that on large collections.

{$group: {
    _id: { iddoc: '$iddoc', type1: '$type1' },
    sum: {$sum: 1},
    matches: { $push: '$$ROOT' }
  }},


来源:https://stackoverflow.com/questions/27907573/keeping-field-in-mongodb-group-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!