Reputation: 14841
I'm trying to fix this little issue, i have trying to search a round to find help, but i can't find help anywhere so i trying to ask here.
i try to get a top most views products from a visitor log, the data in my mongodb look like this
{
"_id" : ObjectId("56617f12cc8eaaa6010041ab"),
"Product" : {
"UUID" : "c7b3e23e-0bf9-4fd5-b8d3-f559b80c42ed"
},
"Log" : {
"Method" : "visit",
"IP" : "127.0.0.1",
"Added" : "2015-12-04 12:54:58"
}
}
What i want is create a group by on the Product.UUID field and all logs not older then 1,5 month and what i have done right now look like this.
db.getCollection('log-product').aggregate([
{
"$group" : {
_id:"$Product.UUID",
total: {$sum : 1}
}
},
{"$sort" : {total: -1}},
{"$limit" : 8}
])
here i group on Product.UUID and sort it DESC on total count and limit it to 8, my problem is i can't find a way to count how many visitor the single product have.
Hope somebody out there can help me width this question.
Upvotes: 0
Views: 111
Reputation: 407
You can filter by Log.Added and group by product uuid and $Log.IP.:
var currentDate = new Date();
var dateOffset = (24*60*60*1000) * 45;
var initInterval = new Date(new Date() - dateOffset);
db.getCollection('log-product').aggregate([
{ "$match" : { "Log.Added": {$lte: currentDate, $gte: initInterval}}},
{
"$group" : {
_id:{"product": "$Product.UUID", "visitor":"$Log.IP"},
total: {$sum : 1}
}
},
{"$sort" : {total: -1}},
{"$limit" : 8}
])
Upvotes: 0
Reputation: 2033
You need to filter "Log.Added" by time interval first then pass the results to $group:
db.getCollection('log-product').aggregate([
{
"$match": {
"Log.Added": { $gt: new Date(2015,10, 15), $lt: new Date(2015,11,15) }
}
},
{
"$group" : {
_id:"$Product.UUID",
total: {$sum : 1}
}
},
{"$sort" : {total: -1}},
{"$limit" : 8}
])
Upvotes: 2