我有一个包含显示用户访问对象的项目的集合:
{"_id" : ObjectId("559d63ac2ea9e7b53ecc3275"),
"user" : {
"id" : "65585",
"cookie" : "spzSznyfDeeFMptiKZqqDg"
},
"object_id" : "3",
"createddate" : ISODate("2015-07-08T17:53:48.209Z")}
我需要按object_id
计算每天的分组数,并在每天选择唯一身份用户并计算它们。
现在我有代码来计算给定对象的视图,并选择查看该对象的不同用户数组。现在我需要数这个用户。
代码是:
db.objects.aggregate([
{"$match": {createddate: {$gt : ISODate("2015-07-01T00:00:00.000Z"), $lte : ISODate("2015-07-15T00:00:00.000Z")}} },
{"$match": {object_id: '1'}},
{"$group": {
"_id": {
"$subtract": [
"$createddate",
{ "$mod": [
{ "$subtract": [ "$createddate", ISODate("1970-01-01T00:00:00.000Z") ] },
1000 * 60 * 60 * 24
]}
]
},
"users": { "$addToSet": "$user"},
"totalviews": { "$sum": 1 }
}},
{ "$sort": { "_id": -1 } }
])
结果是:
{
"result" : [
{
"_id" : ISODate("2015-07-08T00:00:00.000Z"),
"users" : [
{
"id" : "65585",
"cookie" : "spzSznyfDeeFMptiKZqqDg"
},
{
"id" : null,
"cookie" : "spzSznyfDeeFMptiKZqqDg"
}
],
"totalviews" : 3
},
{
"_id" : ISODate("2015-07-07T00:00:00.000Z"),
"users" : [
{
"id" : null,
"cookie" : "spzSznyfDeeFMptiKZqqDg"
},
{
"id" : "65585",
"cookie" : "spzSAAAAAAAAAAMptiKZqqDg"
},
{
"id" : "65585",
"cookie" : "spzSznyfDeeFMptiKZqqDg"
}
],
"totalviews" : 19
}
],
"ok" : 1
}
但我需要结果如下:
{
"result" : [
{
"_id" : ISODate("2015-07-08T00:00:00.000Z"),
"userscount" : 2,
"totalviews" : 3
},
{
"_id" : ISODate("2015-07-07T00:00:00.000Z"),
"userscount" : 3,
"totalviews" : 19
}
],
"ok" : 1
}
不知道如何在mongodb中执行它。
答案 0 :(得分:3)
使用 $size
运算符获取用户数组中项目的总数:
db.objects.aggregate([
{"$match": {createddate: {$gt : ISODate("2015-07-01T00:00:00.000Z"), $lte : ISODate("2015-07-15T00:00:00.000Z")}} },
{"$match": {object_id: '1'}},
{"$group": {
"_id": {
"$subtract": [
"$createddate",
{ "$mod": [
{ "$subtract": [ "$createddate", ISODate("1970-01-01T00:00:00.000Z") ] },
1000 * 60 * 60 * 24
]}
]
},
"users": { "$addToSet": "$user"},
"totalviews": { "$sum": 1 }
}},
{
"$project": {
"totalviews": 1,
"userscount": { "$size": "$users" }
}
},
{ "$sort": { "_id": -1 } }
])