Map-Reduce Function in mongo

150 views
Skip to first unread message

justin

unread,
Jun 12, 2012, 2:32:07 AM6/12/12
to mongodb-user
I have a mongo structure like below
[_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
)

I need to array sum of news(here sum => 14) and add to main
collection with a additional field as sum.

[_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
)
[sum]=> 14

I have more than 3 lakhs records to be done like this every day.

How it can be done with map-reduce or with group ?

Sam Millman

unread,
Jun 12, 2012, 3:15:57 AM6/12/12
to mongod...@googlegroups.com
If you emit on _id and create the sum field so you have a doc that looks like:


{_id: {}, sum: 14}

Then you can merge the output with the old collection (or reduce I keep forgetting which will get desired output here, but merge should do it) then it will basically add that new field on.


--
You received this message because you are subscribed to the Google
Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com
To unsubscribe from this group, send email to
mongodb-user...@googlegroups.com
See also the IRC channel -- freenode.net#mongodb

justin

unread,
Jun 12, 2012, 10:02:36 AM6/12/12
to mongodb-user
Is it possible to new collection(news) with following structure

{id: 454, sum: 14}

Can you please give me demo on map-reduce function here ...

I am new to mongo ..

Thanks in Advance

Jeremy Mikola

unread,
Jun 12, 2012, 5:18:45 PM6/12/12
to mongod...@googlegroups.com
If the goal is the store a sum field on each document, equal to the sum of the values in the news hash, it may be easier to do this without map/reduce.

Consider the following code example: http://pastebin.com/mU8ucqdP

I iterate over the collection using find(), apply snapshotting (see the linked documentation), calculate the sum in PHP, and update the sum field accordingly. Building upon this, you could do atomic updates when adding a new entry to the news field. As you $set a new key in the news object, you can $inc the sum field accordingly. Then, you could reserve the code example for initializing the sum fields or resetting them if things happen to get out of sync.

The equivalent summation (from my code example) could be done with map/reduce, but you'd be calculating the array sums in Javascript (possibly slower in practice) and then you'd still have to issue updates for each document.
Reply all
Reply to author
Forward
0 new messages