我正在尝试运行一个mongodb查询,每天请求它将返回不同列中唯一值的计数。例如,对于6月份,查询将返回日期以及日期中b列中的不同值的计数。任何人都知道如何做到这一点我尝试了几个不同的东西,没有运气
下面是几个示例文档,以及输出应该是什么
{
"_id" : ObjectId("578fa05a7391bb0d34bd3c28"),
"IP" : "123.123.123.123",
"datetime" : ISODate("2016-07-20T10:04:56-05:00")
},
{
"_id" : ObjectId("578fa05a7391bb0d34bd3c28"),
"IP" : "110.123.1.2",
"datetime" : ISODate("2016-07-20T10:04:56-05:00"),
}
输出应为
{
"date":"2016-07-20",
count:2 -- this is distinct number of IPs for the date above
}
答案 0 :(得分:2)
使用aggregate
,您可以执行以下操作:
$project
$group
这2个项目用于将日 - 月 - 年分成新的字段,在$group
mongo查询是:
db.device.aggregate([{
$project: {
_id: 1,
IP: 1,
day: {
"$dayOfMonth": "$datetime"
},
month: {
"$month": "$datetime"
},
year: {
"$year": "$datetime"
}
}
}, {
$project: {
_id: 1,
IP: 1,
datetime: {
$concat: [{
$substr: ["$year", 0, 4]
},
"-", {
$substr: ["$month", 0, 2]
},
"-", {
$substr: ["$day", 0, 2]
}
]
}
}
}, {
$group: {
_id: {
date: "$datetime",
IP: "$IP"
}
}
}, {
$group: {
_id: "$_id.date",
count: {
$sum: 1
}
}
}])
$sum:1
用于统计字段
它会给你这样的东西:
{ "_id" : "2016-7-20", "count" : 2 }
{ "_id" : "2016-8-20", "count" : 1 }
输入数据:
> db.device.find()
{ "_id" : ObjectId("578fa05a7391bb0d34bd3c28"), "IP" : "123.123.123.123", "datetime" : ISODate("2016-07-20T15:04:56Z") }
{ "_id" : ObjectId("578fa05a7391bb0d34bd3c29"), "IP" : "110.123.1.2", "datetime" : ISODate("2016-07-20T15:04:56Z") }
{ "_id" : ObjectId("578fa05a7391bb0d34bd3c25"), "IP" : "110.123.1.2", "datetime" : ISODate("2016-07-20T15:04:56Z") }
{ "_id" : ObjectId("578fa05a7391bb0d34bd3c30"), "IP" : "110.123.1.2", "datetime" : ISODate("2016-08-20T15:04:56Z") }
{ "_id" : ObjectId("578fa05a7391bb0d34bd3c12"), "IP" : "110.123.1.2", "datetime" : ISODate("2016-08-20T15:04:56Z") }