Unexpected outcome observed with straightforward MongoDB MapReduce task

For the past few hours, I've been struggling with a seemingly simple issue. I have a collection of documents that all have the same structure:

{
   "_id": "736722976",
   "value": {
     "tag_cloud": {
       "0": {
         "0": "FIFA World Cup 2014",
         "1": " Germany",
         "2": " Algeria",
         "3": " Thomas Muller",
         "4": " Mesut Ozil"
      },
       "1": {
         "0": "Monsoon",
         "1": " Germany"
      }
    }
  }
}

I'm attempting to run a map-reduce operation on this data to count the total occurrences of each tag in the cloud. Here's what my code looks like:

var map = function(){
  emit(this._id, this.value.tag_cloud);
}

var reduce = function(key, values){
    var mm = new Array();
    values.forEach(function(v){
        for (i in v){
            k = v[i].trim();
            if (k in mm){
                mm[k] = mm[k] + 1;
            }else{
                mm[k] = 1;
            }
        }
    });
    return {tag: mm};
}

db.analysis_mid.mapReduce(map, reduce, 
        {
            out: "analysis_result"
        }
);

I execute the script using the following command:

mongo localhost:27017/my_db_name_with_mother_collection mr.js

The code runs without any errors, but the output it generates is not as expected:

{
   "_id": "736722976",
   "value": {
     "0": {
       "0": "FIFA World Cup 2014",
       "1": " Germany",
       "2": " Algeria",
       "3": " Thomas Muller",
       "4": " Mesut Ozil"
    },
     "1": {
       "0": "Monsoon",
       "1": " Germany"
    }
  }
}

I am puzzled by this outcome and unsure of what I might be overlooking. Can anyone offer some assistance?

The desired result should look like this:

{ 
    "_id": "736722976",
    "tag": {
        "FIFA World Cup 2014": 1,
        "Germany": 2,
        "Algeria": 1,
        "Thomas Muller": 1,
        "Mesut Ozil": 1,
        "Monsoon": 1
    }
}

Thank you for your help.

Answer №1

I have identified several issues with the code. Firstly, the variable mm is an object and not an array, so you need to use a string key instead. Secondly, you cannot use the forEach() method on an object; you would need to use a for loop instead.

It appears that there is an error in the code (specifically the forEach() function), causing the reduce method not to be executed as expected.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Managing a high volume of HTTP requests within a React-Redux application

Seeking assistance with my react-redux app project. I have a substantial amount of data that has been divided into smaller files, allowing the user to choose a start and end time range. Upon clicking the "Fetch data" button, I create HTTP request promise ...

Perform DOM manipulation prior to triggering the AJAX event to prevent CSRF Error

Currently, I am faced with a challenge while working on Django. My goal is to implement a chained AJAX call - meaning that once one call returns, it triggers additional AJAX calls. Despite thorough research and referencing the suggested methods in the Djan ...

Generate an array of identifiers from a pre-existing array

I am facing a challenge where I need to create an array of IDs for each element in an existing array whose size is unknown. The twist here is that every set of four elements should have the same ID. As an illustration, if the original array (let's ca ...

What is the best way to enable one directive to be utilized across multiple inputs in Angular Material?

Here is a code snippet that I am working with: <md-input-container class="new-paragraph addon-menu"> <label>Post text</label> <textarea ng-model="user.post" rows="3"></textarea> </md-input-container> <md-menu ...

Tips on redirecting the user to the page they have selected

<section> <div class="container"> <select name="semester" id="select-semester"> <option value="no-semester">choose a semester</option> <option valu ...

Has xlink:href become outdated for svg <image> elements?

In the realm of SVG attributes, it is noted by MDN xlink:href that href should be used over xlink:href. Interestingly, on the svg example page, last revised on July 6, 2017, the attribute utilized in the given example is xlink:href. The question arises: ...

Deep-diff JavaScript functions are not permissible for use

In my AngularJS application, I am currently attempting to utilize a JavaScript package. To reference it in my index.html file, I added the following code: <script src="deep-diff-0.3.1.min.js"></script> Furthermore, in my controller, I am usin ...

Retrieve the XML file from the webpage and save it to a specific directory using Java and the Selenium framework with the Chrome browser

Retrieve xml file from the website and save it to a specific location using java or selenium with Chrome browser. Here is the snippet of HTML code: <!-- Start of Code which handles XML Download--> <a href="javascript:downloadXML()"> <img s ...

Presence detected: Discord bot appears online but is missing from members list

I am embarking on the journey of creating my first Discord bot. After installing NodeJS on my computer, I used the Discord developer tools to create the app, turned it into a bot, obtained the token, selected privileges, and added the bot to my server. I ...

Achieving the functionality of keeping the search query box and alphabetical search options visible on the page even after performing a search and displaying the results can be done by

I have set up a PHP page with search query field and alphabetical search options. When submitting the query, the results are displayed on the same page; however, I would like the results to show in the same location as the alphabetical search. Currently, ...

Tips for adding extra spacing between icon and text field using Vuetify

The code snippet below is used for the username section: <v-text-field prepend-icon="fas fa-user" height="60px" placeholder="Username" outlined ></v-text-field> Is there a way to add space between the user ...

how can I convert div attributes into JSON format

I am working with the following div element: <div class="specialbreak"> This div has been saved in a JavaScript variable. My goal is to convert this div into JSON format so that I can easily access the class name. Although I attempted to use JSON ...

Importing D3 data from CSV files using the "%" symbol

I am trying to import a CSV file with the following data: Month, Ratio January, 0.19% February, 0.19% March, 0.19% April, 0.18% The current code snippet I'm using is as follows: d3.csv("month_ct.csv", function(d) { return { month: d ...

What is the reason JSON.parse fails to convert a string into a JSON object?

I attempted to convert a string into a JavaScript object using JSON.parse, however, it seems to be unsuccessful. After trying various methods, I did not receive any output in the console.log and no error messages were displayed. JSON.parse(`{'exp&apo ...

Obtaining a document through an Anchor Element

I am currently implementing a feature to allow users to download a zip file using an anchor tag. Here's how it's set up: <a href="download/sample.zip">sample.zip</a> When the file exists in the download directory, everything works s ...

Choosing a particular 2D array based on another variable in jQuery and JavaScript

Within my project, I am utilizing 2D arrays to append specific divs under particular circumstances. In an effort to streamline and enhance the code, I attempted to create a variable that would determine which array to utilize based on the id of an HTML < ...

Troubleshooting issue with Jquery animation from left to right

What's the issue with this code? It is supposed to animate the arrow from left to right and then back to left again repeatedly, but it's not working as expected. Any ideas on why that might be? function moveRight(){ $('#myIcon'). ...

Is the $ajax() function truly asynchronous when invoking a success callback?

I find myself in a state of confusion at the moment. The asynchronous ajax call I have set up includes a success callback function being passed in. ajax('PUT', 'some URL', successCallback, data); I notice that this callback is trigger ...

What is the process for toggling a button using Vue.js?

Important Note: Implemented Vue.js and Vuetify.js for both functionality and styling. Utilizing the :class and @click properties, I managed to alter the background color of a button to a specified color. However, this modification is being applied to all ...

Troubleshooting problem with accessing Mongoid

I am currently developing an application with a database embedded in it. The database I am using is MongoId, containing only one entry which stores a token. api.rb def get_wink_token retrieve_token.present? ? retrieve_token : new_token end ...