Mongodb: count items by date, then count unique items

I have a collection with elements that show user visits by such objects:

{"_id" : ObjectId("559d63ac2ea9e7b53ecc3275"), "user" : { "id" : "65585", "cookie" : "spzSznyfDeeFMptiKZqqDg" }, "object_id" : "3", "createddate" : ISODate("2015-07-08T17:53:48.209Z")} 

I need to count them every day in the object_id group and select unique users and count them every day. Now I have a code that takes into account the views of this object and selects a separate array of users viewing this object. Now I need to count these users. Code:

 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:

 { "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 } 

But I need the result:

 { "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 } 

I don't know how to do this in mongodb.

+6
source share
1 answer

Use the $size operator to get the total number of elements in an array of users:

 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 } } ]) 
+3
source

All Articles