I’m trying to do a group query on a mongoDB but I get a wrong result and with all the tweaks it doesn’t solve my problem.
I have a collection with the following schema (action_ is a counter)
"_id": ObjectId(""),
"action_1": 3,
"action_2": 2,
"action_4": 0,
"shop": ObjectId(""),
"user": ObjectId(""),
"action_3": 33
I need for each user to sum all counters from all shops, and I’ve did this:
$keys = array("action_1"=>1, "action_2"=>1, "action_3"=>1, "action_4"=>1);
$initial = array("action_1"=>0, "action_2"=>0, "action_3"=>0, "action_4"=>0);
$reduce = "function (obj, prev) {
prev.action_1 += obj.action_1;
prev.action_2 += obj.action_2;
prev.action_3 += obj.action_3;
prev.action_4 += obj.action_4;
}";
$condition = array('user' => $user_id);
$g = $collection->group($keys, $initial, $reduce, $condition);
The result I get is an array of documents that extract the values. I need an array of associative arrays, and for every user to have something like:
array ("user") {
action_1 => sum, //integer
action_2 => sum,
action_3 => sum,
action_4 => sum
}
You will want to group by the
userkey instead then: