whether mongodb mapreduce function accepts calculated value of document as a mapper

Viewed 50

I use MongoDB version 2.6.10. Below is the collection structure. I use MapReduce function to group the names of the user based on (created(excluding seconds), event_name.

{
    "_id" : ObjectId("59c11d79078dc54153c36ee8"),
    "event_name" : "notification",
    "created" : ISODate("2017-09-19T13:36:57.252Z"),
    "sender_name" : "nathan",
    "user_name": "Ragul"",
}
{
    "_id" : ObjectId("59c11d79078dc54153c36eeb"),
    "event_name" : "notification",
    "created" : ISODate("2017-09-19T13:36:57.772Z"),
    "sender_name" : "parmesh",
    "user_name": "Ram",
}
{
    "_id" : ObjectId("59c11d7a078dc54153c36ef0"),
    "event_name" : "notification",
    "created" : ISODate("2017-09-19T13:36:58.554Z"),
    "sender_name" : "nathan",
    "user_name": "Ram",

}
{
    "_id" : ObjectId("59c11d7a078dc54153c36ef1"),
    "event_name" : "message",
    "created" : ISODate("2017-09-19T13:36:58.577Z"),
    "sender_name" : "nathan",
    "user_name": "Ragul"",
}

Below is my query using MapReduce function. My question is whether we can use calculated date as a mapper. Help me with your suggestions

var mapfn = function(){
    if (this.event_name == "message"){
        name = this.recipient_name
    }
    else if ((this.event_name == "notification") && (this.other_status == true)){
        name = this.sender_name
    }
    else if ((this.event_name == "notification") && (this.other_status == false)){
        name = "You"
    }
    this.cre = {$subtract:[this.created,{$add:[{$multiply:[{$second:this.created},1000]},{$millisecond:this.created}]}]}
    emit({"event_name": this.event_name, "created": this.cre}, name)
}

var redfun = function(key, value){
    return Array.append(value)
}

db.getCollection('users').mapReduce(mapfn, redfun, {out: "example"}).find()
1 Answers

Here instead calculating the date using MongoDB expression, I tried to use javascript to eliminate the seconds and then I mapped then its worked.

var mapfn = function(){
    if (this.event_name == "message"){
        name = this.recipient_name
    }
    else if ((this.event_name == "notification") && (this.other_status == true)){
        name = this.sender_name
    }
    else if ((this.event_name == "notification") && (this.other_status == false)){
        name = "You"
    }
    this.created.setSeconds(0);
    this.created.setMilliseconds(0);
    emit({"event_name": this.event_name, "created": this.created}, name)
}

var redfun = function(key, value){
    var names = value.join(",")
    return names
}

db.users.mapReduce(mapfn, redfun, {out: "example"}).find()
Related