How can I do a query in Mongodb to find the count of entry and exit group by user for a location. the above collection have many locations for which user can enter or exit.
{ "ActivityList" : [
{ "type" : "entry",
"timestamp" : Date( 1344473257320 ),
"user" : { "$ref" : "userProfile",
"$id" : ObjectId( "4fdeaf6fde26fd298262bb81" ) } },
{ "type" : "exit",
"timestamp" : Date( 1348792321111 ),
"user" : { "$ref" : "userProfile",
"$id" : ObjectId( "4fdeaf6fde26fd298262bb81" ) } },
{ "type" : "entry",
"timestamp" : Date( 1348881701129 ),
"user" : { "$ref" : "userProfile",
"$id" : ObjectId( "4fdeaf6fde26fd298262bb81" ) } },
{ "type" : "exit",
"timestamp" : Date( 1348942808700 ),
"user" : { "$ref" : "userProfile",
"$id" : ObjectId( "4fdeaf6fde26fd298262bb81" ) } },
{ "type" : "entry",
"timestamp" : Date( 1348957400052 ),
"user" : { "$ref" : "userProfile",
"$id" : ObjectId( "4fdeaf6fde26fd298262bb81" ) } },
{ "type" : "exit",
"timestamp" : Date( 1349024290729 ),
"user" : { "$ref" : "userProfile",
"$id" : ObjectId( "4fdeaf6fde26fd298262bb81" ) } } ],
"Loc" : { "$ref" : "location",
"$id" : ObjectId( "501cb6d4e7e9a8f958f903c5" ) },
"_id" : ObjectId( "502308a9e7e91ab176f6708e" ) }
I am trying something like this but not successful ,see here
select a,b,sum(c) csum from coll where active=1 group by a,b
db.coll.group(
{key: { a:true, b:true },
cond: { active:1 },
reduce: function(obj,prev) { prev.csum += obj.c; },
initial: { csum: 0 }
});
The document structure you are using (an array of items) will require some manipulation in the
$group()function that would be easier done with MapReduce or the new Aggregation Framework in MongoDB 2.2.Here’s an example using the Aggregation Framework:
Which produces a result similar to: