Mongodb 对不同的事件进行分组和计数
我试图派生一个查询,以获得不同值的计数并显示相关字段。分组由Mongodb 对不同的事件进行分组和计数,mongodb,distinct,aggregation-framework,robo3t,Mongodb,Distinct,Aggregation Framework,Robo3t,我试图派生一个查询,以获得不同值的计数并显示相关字段。分组由tempId和date完成,其中tempId可以在一天和一个时间范围内发生一对多次 以下是我的做法, db.getCollection('targetCollection').aggregate( { $match:{ "user.vendor": 'vendor1', tool: "tool1", date: {
tempId
和date
完成,其中tempId
可以在一天和一个时间范围内发生一对多次
以下是我的做法,
db.getCollection('targetCollection').aggregate(
{
$match:{
"user.vendor": 'vendor1',
tool: "tool1",
date: {
"$gte": ISODate("2016-04-01"),
"$lt": ISODate("2016-04-04")
}
}
},
{
$group:{
_id: {
tempId: '$tempId',
month: { $month: "$date" },
day: { $dayOfMonth: "$date" },
year: { $year: "$date" }
},
count: {$sum : 1}
}
},
{
$group:{
_id: 1,
count: {$sum : 1}
}
})
此查询生成以下输出:
{
"_id" : 1,
"count" : 107
}
这是正确的,但是,我想用日期和该日期的具体计数来分隔它们。比如说像这样的事情,
{
"date" : 2016-04-01
"count" : 50
},
{
"date" : 2016-04-02
"count" : 30
},
{
"date" : 2016-04-03
"count" : 27
}
另外,我不知道如何把这个问题放在一起,因为我对这项技术相当陌生。请让我知道问题是否需要改进
下面是我试图查询的mongodb集合的示例数据
{
"_id" : 1,
"tempId" : "temp1",
"user" : {
"_id" : "user1",
"email" : "user1@email.com",
"vendor" : "vendor1"
},
"tool" : "tool1",
"date" : ISODate("2016-03-09T08:30:42.403Z")
},...
按日期分组
我自己已经想出了解决办法。我所做的是
- 我首先按照
tempId
和date
- 然后,我按日期分组
这打印出了每日不同的tempId
计数,这是我想要的结果。查询如下:
db.getCollection('targetCollection').aggregate(
{
$match:{
"user.vendor": 'vendor1',
tool: "tool1",
date: {
"$gte": ISODate("2016-04-01"),
"$lt": ISODate("2016-04-13")
}
}
},
{
$group:{
_id: {
tempId: "$tempId",
month: { $month: "$date" },
day: { $dayOfMonth: "$date" },
year: { $year: "$date" }
},
count: {$sum : 1}
}
},
{
$group:{
_id: {
month:"$_id.month" ,
day: "$_id.day" ,
year: "$_id.year"
},
count: {$sum : 1}
}
})
感谢您的回答,但是需要考虑tempId
。我试图导出的查询是获取给定日期范围内每天不同的tempId
的count
。我已经更新了问题。:)嘿,谢谢,但我想它更近了,但它和我一样。日期应该像我做的那样做,因为时间戳包含秒,所以分组无论如何都会给出一个值。我需要得到每天的distincttempId
s的总计数。
db.getCollection('targetCollection').aggregate(
{
$match:{
"user.vendor": 'vendor1',
tool: "tool1",
date: {
"$gte": ISODate("2016-04-01"),
"$lt": ISODate("2016-04-13")
}
}
},
{
$group:{
_id: {
tempId: "$tempId",
month: { $month: "$date" },
day: { $dayOfMonth: "$date" },
year: { $year: "$date" }
},
count: {$sum : 1}
}
},
{
$group:{
_id: {
month:"$_id.month" ,
day: "$_id.day" ,
year: "$_id.year"
},
count: {$sum : 1}
}
})