Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8081225
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T16:39:54+00:00 2026-06-05T16:39:54+00:00

Need a map reduce function by mongo in php This my mongo structure [_id]

  • 0

Need a map reduce function by mongo in php

This my mongo structure

[_id] => MongoId Object (
    [$id] => 4fcf2f2313cfcd2454500000d
)
[id] => 454
[table] => people
[news] => Array (
    [03-06-2012] => 2
    [04-06-2012] => 3
    [05-06-2012] => 5
    [06-06-2012] => 4
)

Here I try to sum the array news with below code,

    $map = new MongoCode('function() { emit(this.news, 1); }');
    $reduce = new MongoCode('function(previous, current) {
                    var count = 0;
                    for (index in current) {
                        count = count + current[index];
                    }
                    return count;
                }');

    $sales = $db->command(array(
        'mapreduce' => 'mycollection',
        'map' => $map,
        'reduce' => $reduce,
        'query' => array('table' => 'people'),
        'out'  => 'news'
    ));

    //pr($sales);exit;

    $users = $db->selectCollection($sales['result'])->find();

    foreach ($users as $user) {
        //echo "{$user['_id']} had {$user['value']} sale(s).\n";
        pr($user);
    }

When pr($user)

Array
(
    [_id] => Array
    (
        [04-06-2012] => 0
        [08-06-2012] => 2
        [11-06-2012] => 6
    )

    [value] => 39540
)

Where I expected a value will be 8 instead of 39540.

How I can correct this function and how to the add a field sum as array sum of ‘news’ to original collection(mycollection) ?

I am not familar with map reduce functions in mongo.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T16:39:56+00:00Added an answer on June 5, 2026 at 4:39 pm

    When calling emit(), the first parameter is the key you’ll be reducing on (or grouping, for this example). The second parameter is the value being emitted for that key, which can be anything. For your example, you probably mean to emit the sum of all values in the news field, using the document’s ID as your key:

    var map = function() {
        var total = 0;
        for (count in this.news) {
            total += count;
        }
        emit(this._id, total);
    }
    

    In this case, a placeholder reduce function can be used (since each emitted key will be unique, there’s very little reduction to be done):

    var reduce = function(key, values) {
        var total = 0;
        values.forEach(function(v) { total += v; });
        return total;
    }
    

    However, as I mentioned in the Google Group post, you may be better off doing this with pure PHP:

    $cursor = $collection->find(array(), array('news' => 1));
    $cursor->snapshot();
    
    foreach ($cursor as $document) {
        $collection->update(
            array('_id' => $document['_id']),
            array('$set' => array('sum' => array_sum($document['news']))),
            array('multiple' => false)
        );
    }
    

    With map/reduce, you’d still have to examine its results and update your records. This would avoid the need to execute JavaScript through Mongo, and should be more performant. And if you can utilize $inc to update the sums as the news field is modified on a per-document basis, that will be even better. The above snippet would still be useful for initializing sum fields across the collection, or correcting any drift if things get out of sync with per-document increments.

    Note: see snapshot() in the documentation for the reasoning behind that method call in the example above.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

If I don't do any map/reduce jobs, still JobTracker/TaskTrackers need to be running for
I'm just learning mapReduce. I have the following map reduce function being called on
I created map/reduce functions to group tasks results in one result object. I wrote
To effectively utilise map-reduce jobs in Hadoop , i need data to be stored
Just learning Map/Reduce and I'm missing a step. I've read this post ( RavenDB
I need function-aggregator, which would reduce two lists to one total number. 'Items' is
I need to map most of the computer memory as uswc to take advantage
I need to map a class which has a list of Enums to a
I need to map a many-to-many relationship using Entity Framework Code First. Its a
I need to map a single fixed sized array array to multiple properties. For

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.