mongodb 聚合管道中的多个组
Multiple groups in mongodb aggregate pipeline
我有一个集合,其中包含如下数据:
{
attribute: 'value',
date: ISODate("2016-09-20T18:51:05Z")
}
我想按 attribute
分组以获得每个属性的总计数,同时按 attribute
和 $hour
分组以获得每个属性和小时的计数。
我知道我可以做类似的事情:
{
$group: {
_id: '$attribute'
count: {
$sum: 1
}
}
}
和
{
$group: {
_id: {
attribute : '$attribute',
hour: {
'$hour' : '$date'
}
},
count: {
$sum: 1
}
}
},
{
$group: {
_id: {
attribute: '$_id.attribute'
},
hours: {
'$push': {
hour: '$_id.hour',
count: '$count'
}
}
}
}
在两个单独的聚合中获得两个结果,但是有没有办法在一个查询中获得我想要的结果?
按要求编辑:
也许这是完全错误的,但理想情况下我希望得到这样的回复:
{
_id: "attribute1",
total: 20, // Total number of attribute1 documents
// And the breakdown of those 20 documents per hour
hours: [{
hour: 10,
count: 8
},
{
hour: 14,
count: 12
}]
}
然而,问题的重点是这是否可以(以及如何)在 mongodb 中的一个查询中完成。不在将在应用程序层上合并的两个查询中
您可以先按属性-小时对及其对应的出现次数进行分组。
然后,您投影属性、一对小时计数和该计数的副本。
最后,您单独按属性分组,$push
对,然后对计数求和。
[
{
$group: {
_id: {
attribute: "$attribute",
hour: { "$hour": "$date" }
},
count: {
$sum: 1
}
}
},
{
$project: {
attribute: "$_id.attribute",
pair: { hour: "$_id.hour", count: "$count" },
count: "$count",
_id: 0
}
},
{
$group: {
_id: "$attribute",
hours: {
$push: "$pair"
},
total: {
$sum: "$count"
}
}
}
]
我有一个集合,其中包含如下数据:
{
attribute: 'value',
date: ISODate("2016-09-20T18:51:05Z")
}
我想按 attribute
分组以获得每个属性的总计数,同时按 attribute
和 $hour
分组以获得每个属性和小时的计数。
我知道我可以做类似的事情:
{
$group: {
_id: '$attribute'
count: {
$sum: 1
}
}
}
和
{
$group: {
_id: {
attribute : '$attribute',
hour: {
'$hour' : '$date'
}
},
count: {
$sum: 1
}
}
},
{
$group: {
_id: {
attribute: '$_id.attribute'
},
hours: {
'$push': {
hour: '$_id.hour',
count: '$count'
}
}
}
}
在两个单独的聚合中获得两个结果,但是有没有办法在一个查询中获得我想要的结果?
按要求编辑:
也许这是完全错误的,但理想情况下我希望得到这样的回复:
{
_id: "attribute1",
total: 20, // Total number of attribute1 documents
// And the breakdown of those 20 documents per hour
hours: [{
hour: 10,
count: 8
},
{
hour: 14,
count: 12
}]
}
然而,问题的重点是这是否可以(以及如何)在 mongodb 中的一个查询中完成。不在将在应用程序层上合并的两个查询中
您可以先按属性-小时对及其对应的出现次数进行分组。
然后,您投影属性、一对小时计数和该计数的副本。
最后,您单独按属性分组,$push
对,然后对计数求和。
[
{
$group: {
_id: {
attribute: "$attribute",
hour: { "$hour": "$date" }
},
count: {
$sum: 1
}
}
},
{
$project: {
attribute: "$_id.attribute",
pair: { hour: "$_id.hour", count: "$count" },
count: "$count",
_id: 0
}
},
{
$group: {
_id: "$attribute",
hours: {
$push: "$pair"
},
total: {
$sum: "$count"
}
}
}
]