0

MongoDB can not get the total.

MYSQL :

select sum(play) as toplam from videos

MongoDB :

    $group = $naytu->db->videos->group(array(), array("toplam" => 0), "function(obj, prev) {prev.toplam = prev.toplam + obj.play - 0;}"); 

results (print_r)

Array
(
[retval] => Array
    (
        [0] => Array
            (
                [toplam] => NAN
            )

    )

[count] => 78656
[keys] => 1
[ok] => 1
)

where is the problem ?

3 Answers 3

3

In PHP @Neils answer is:

$mongo->videos->aggregate([
    ['$group' => ['_id' => null, 'toplam' => ['$sum' => '$play']]]
]);
Sign up to request clarification or add additional context in comments.

Comments

0

The group() function is kind of an old form of achieving results like this, it will also not work with sharded collections. Better to familiarize yourself with aggregate:

db.collection.aggregate([

    {"$group": { "_id": null, "toplam": {"$sum": "$play"} }}

]);

Output for you driver will just be a cursor just like using find.

for PHP Syntax

For the record, your usage seems to be way off. Much as above you just translate the relative JSON to Dicts, and if that is still a problem then use a JSON parser to show you how. All the arguments are valid JSON, so I'm reminding myself to do this for all examples now, so people can easily dump into their own language.

 db.collection.group({
     "key": {},
     "reduce": "function(curr, result) { result.total += curr.play;  }",
     "initial": { "total": 0 } 
 })

But still, don't use this anyway. Stick to aggregate, it's a useful tool to learn.

Of course in all cases, make sure that all your data being applied to a sum is actually a number, or things will blow up on you.

2 Comments

@user3342378 See the link. Google is your friend ;)
@user3342378 if you're still struggling with this the edits should help you.
0

Maybe this can help

"function(obj, prev) {prev.toplam = new NumberInt(prev.toplam) + new NumberInt(obj.play);}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.