将字段保留在mongodb中 [英] Keeping field in mongodb group by

查看:66
本文介绍了将字段保留在mongodb中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

{_id:xx,

{ _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:

type1在["type1A","type1B",...]中,其中type2在["type2A","type2B",...] date.year:2015,date.month:4,date.type:在4到7之间的天" date.day

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?

推荐答案

我相信此查询可以解决您的要求:

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

关于如何查看其余字段,有一些选项.我选择将type2推入数组(允许重复),取 year month 的第一个值,因为匹配操作始终为2015和4,和 addToSet 插入数组的日期(不允许重复).另一种选择是将整个文档放入匹配的数组中,但是在大型集合中应格外小心.

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' }
  }},

这篇关于将字段保留在mongodb中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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