Update inside the map function of map/reduce

14 views
Skip to first unread message

Martinus Martinus

unread,
Nov 5, 2012, 4:57:19 AM11/5/12
to mongod...@googlegroups.com
Hi,

Can I do update inside the map function for the same document? for example I have something like below :
{
    "_id" : 1,
    "name" : "Bob",
    "species" : "Penguin",
    "eat" : 4,
    "status" : 0
},
{
    "_id" : 2,
    "name" : "Ray",
    "species" : "Tiger",
    "eat" : 10,
    "status" : 1
}

So I do filtering at the beginning before I do the map/reduce with below filtering :
BasicDBObject filter = new BasicDBObject();
filter.put("status", new BasicDBObject("$ne", 0));

MapReduceOutput out = animal_collection.mapReduce(map, reduce, out, MapReduceCommand.OutputType.MERGE, filter);

And my map function looks like below :
function(){
     var _id = this._id;
     var name = this.name;
     var eat = this.eat;
     var species = this.species;
     db.animal_collection.update({_id : _id}, { $set : { status : 0}});
     emit(species, 
     {
         name : name, 
 eat : eat,
         species : species
     }
}

reduce :
function(key, values){
    var total = 0;
    for(var i=0; i<values.length; i++)
    {
total += values[i].eat;
    }
    var result = values[0];
    result.eat = total;
    return result;
}

Can I do updating like above, since it will directly update into only single document and on the same shard?

Thanks.

Sam Millman

unread,
Nov 5, 2012, 5:32:56 AM11/5/12
to mongod...@googlegroups.com
"Can I do updating like above, since it will directly update into only single document and on the same shard?"

Don't see how the JS engine can know that.

The db object was obsoleted a long time ago due to the scaling problems of it so you will need to find a different way around this. Status seems like a optimistic lock of some kind, so you could replace it in many ways i.e. grab the last _id client side, save it to another collection and use that to range.


--
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

Martinus Martinus

unread,
Nov 5, 2012, 5:44:26 AM11/5/12
to mongod...@googlegroups.com
Hi Sam,

Thanks for your answer. Basically what I'm trying to do is filter the data that is new or updated ones to become the input for map/reduce function, so the old document which doesn't change will not be calculated again. Is there any mongodb operator to do this?

Thanks.
Reply all
Reply to author
Forward
0 new messages