mongodb map-reduce returns wrong values

107 Views Asked by At

I wrote a few months back map-reduce functions, when I checked it worked as expected. Now I'm trying to run the same functions with similar data and get weird results.

I've tested my old code in this simulator: http://targetprocess.github.io/mongo-mapreduce-debug-online/ and it works as I expect.

there is the map function:

map(){
    const report = {
         clicks: 1
    };
    const baseKey = {date: this.date}
      const attrs = ['country']
         attrs.forEach(attr => {
        let docKey = { ...baseKey, extId: this.extId, attr };
        emit(docKey, { report, attrValue: this[attr]})
    })
}

example document:

{
        "_id" : ObjectId("5f86b5c240d9925e4ccab199"),
        "extId" : ObjectId("5f8475154f8ee65494e5320a"),
        "country" : "DE",
        "date" : ISODate("2020-10-14T00:00:00Z"),
        "time" : ISODate("2020-10-14T08:24:34.649Z"),
      "__v" : 0
}

I tried the simplest reduce function:

reduce(key, values){
   return 1
}

I should get:

  {
    "_id": {
      "date": "2020-10-14T00:00:00.000Z",
      "extId": "5f8475154f8ee65494e5320a",
      "attr": "country",
    },
    "value": 1
  }

But I'm getting:

   {
        "_id" : {
            "date" : ISODate("2020-10-14T00:00:00Z"),
            "table" : ObjectId("5f8475314f8ee65494e5320b"),
            "attr" : "country"
         },
         "value" : {
             "report" : {
                  "clicks" : 1,
              },
              "attrValue" : "DE"
         }
   }

It looks like it returning the value from the emit, and I can't find any reason for failing to return 1 like it should.

Edit: I found out this happens when the query I supply to the mapReduce match with 1 document (even though the map function emits more than once). When it has more than 1 document it works as expected.

How can I solve it?

1

There are 1 best solutions below

0
On

MongoDB skip the reduce function if a certain key has only 1 value. and apparently I did some mapping in the reduce function which is wrong. I changed the output of the mapping to match the structure of the reduce output and it works like it should.

This was very helpful: https://stackoverflow.com/a/22095649/9103301