将字段保留在 mongodb 组中

use*_*783 0 mongodb aggregation-framework

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

{_id:xx,

iddoc:yy,   

type1:"sometype1", 

type2:"sometype2",

date: 

{ 

  year:2015,

  month:4,

  day:29,

  type:"day"

},

count:23  }
Run Code Online (Sandbox Code Playgroud)

我想对所有文档按 iddoc 分组的字段计数求和,其中:

type1 in ["type1A","type1B",...] where type2 in ["type2A","type2B",...] date.year: 2015, date.month: 4, date.type: "day" date.day 介于 4 和 7 之间

然后我想对这些总和进行排序。

我现在知道怎么做(见这个问题

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}}
])
Run Code Online (Sandbox Code Playgroud)

但希望匹配操作中的某些字段出现在最终文档中。这可能吗?如何?

NoO*_*let 5

我相信此查询是您所要求的解决方案:

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}}
])
Run Code Online (Sandbox Code Playgroud)

有一些选项可以显示您希望如何查看其余字段。我选择将 type2 推送到一个数组(允许重复),取第一个值yearmonth因为每次匹配操作将始终为 2015 和 4,并将addToSet日期推送到数组(不允许重复)。另一种选择是将整个文档推送到一组匹配项中,但在大型集合上应该小心。

{$group: {
    _id: { iddoc: '$iddoc', type1: '$type1' },
    sum: {$sum: 1},
    matches: { $push: '$$ROOT' }
  }},
Run Code Online (Sandbox Code Playgroud)