using java to invoke a server-side function within a mapReduce operation in mongodb

i have saved two functions in the "system.js" collection under the names "mapfun" and "reducefun" and now i am attempting to invoke these functions from Java. I am trying to utilize MapReduceCommand for this purpose but encountering difficulties in calling them. Could someone provide assistance on this matter? The structure of the two functions is as follows: //mapfun

{ "_id" : "mapfun","value" : { "code" : "function(){var criteria; if(this.speed > 70 ){ criteria="overspeed";emit(criteria,this.speed); } }" } }

//reducefun

{ "_id" : "reducefun", "value" : { "code" : "function(key,speed){ var total=0; for(var i=0;i<speed.length;i++){ total=total+speed[i]; } return total/speed.length; }" } }

The code for my mapreducecommand is shown below:

MapReduceCommand command=new MapReduceCommand(collection, map, reduce, null, MapReduceCommand.OutputType.INLINE, null);
MapReduceOutput output=collection.mapReduce(command);

I have passed the map and reduce functions as strings wherein I attempted to call the mapfun and reducefun respectively as demonstrated below:

String map = "function (){var x=mapfun();"
                + "return x;};";
String reduce = "function(key, speed) {var y=reducefun(key,speed);"
                + "return y;};";

If there are any errors in my approach or if corrections need to be made, please advise me accordingly.

Answer №1

The root issue lies in the fact that the this variable gets reassigned with each function invocation.

To illustrate this, I conducted a brief test using the mongo shell.

Firstly, I created a collection with 1 document:

MongoDB Enterprise replset:PRIMARY> db.maptest.find({},{_id:0})
{ "canary" : "tweet" }

Next, I defined a stored function that takes an argument and outputs two values - one utilizing this and the other utilizing the provided argument:

MongoDB Enterprise replset:PRIMARY> db.system.js.find()
{ "_id" : "testfun", "value" : { "code" : "function(arg){emit(\"this.canary\",this.canary),emit(\"arg.canary\",arg.canary)}" } }

Subsequently, I utilized the stored function in a mapReduce operation:

MongoDB Enterprise replset:PRIMARY> db.maptest.mapReduce(function(){testfun(this)},function(a,b){return {a:a,b:b}},{out:{inline:1}})
{
    "results" : [
        {
            "_id" : "arg.canary",
            "value" : "tweet"
        },
        {
            "_id" : "this.canary",
            "value" : undefined
        }
    ],
...

It is evident that while this.canary was undefined, arg.canary held the value from the input document.

During a mapReduce operation, the framework sets this to the current document being processed when invoking the map function. When the stored function is invoked within the map function, it acquires its own context for this. Nonetheless, by calling the function as testfun(this), the original this context of the map function is passed to the stored function as an argument.

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

Create a compass application using React-Native

I am attempting to create a compass, but I am unsure how to utilize the Magnetometer data. Below is my Compass class: class Compass extends Component { constructor(props) { super(props); } componentWillMount(){ this._animeRotation = new Ani ...

Implementing child components rendering in a React application using TypeScript

Just a little background information: I am attempting to build a carousel with pagination using ReactJS. Here is the code snippet I currently have: interface HTMLCarouselT { children: Array<JSX.Element> size: number; } const HTMLCarousel = ({ch ...

Switching the default browser for npm live-server

When I use the npm live-server package to preview my website as it changes, it keeps opening in Edge even though Chrome is set as my default browser on my system. I attempted to use the command suggested on the npm website: live-server --browser=chrome H ...

unable to adjust the maximum height limit

I've been struggling to set a maximum height on the slider I'm currently using. No matter what height value I input, it doesn't seem to take effect. Additionally, I attempted setting the width for the echo img row in the PHP section but enco ...

Embedding a thread in an HTML document (Difficult task)

I'm currently working on a method to achieve the following task: Embedding a specific string (such as "TEST") into the content of an HTML page, after every certain number of words (let's say 10). The challenge here is ensuring that the word count ...

Can you explain the functionality of the NextSibling method?

I have a question about how the property NextSibling behaves when using the method getElementsByClassName(). Let me illustrate the issue with this code example: function Sibling() { var x = document.getElementsByClassName('firstClass')[0]; ...

Programmatically switch between show and hide using Angular Material

Is there a way to programmatically toggle between displaying and hiding attributes by clicking a button? For example, I have a card that includes both a map and a list view. Normally, these are shown side by side. However, on mobile devices, the list view& ...

What is the best way to ensure that lessons for the same group of students are grouped together in the same Timeslot and Room in Optaplanner?

I am aiming to ensure that student groups from the same series are scheduled in the same Timeslot and Room for a specific Course Type. Here is my proposed solution: Constraint enforceGroupingInSameTimeslot(ConstraintFactory constraintFactory){ ret ...

Guide to showcasing an Expo camera image in a React Native app

I have been working on an app that involves camera functionality. I have successfully taken a picture and converted it into base64 format. However, I am facing an issue when trying to display the image. Can someone please assist me in achieving this goal? ...

Halt the execution of a function upon clicking a div element

I'm currently working on a function that needs to be stopped when a div with the class "ego" is clicked. This function toggles the visibility of the header based on the scroll position and should only run by default. Below is the code snippet: $("#e ...

How can I filter rows in HTML using Vue.js based on string options?

When selecting different options, I want to dynamically add new rows. For instance, if "kfc" is selected, a specific row should be added. If "cemrt" is chosen, another row needs to be included. <div class="card-content" v-for="(bok, index) in rules" :k ...

Having difficulty completing the text field and submitting it automatically

My goal is to automatically fill in the "Reason for Access" text box with the word "TEST" using Tampermonkey. I am new to using Tampermonkey and UserScript, so I appreciate your patience. Currently, I am facing an issue where the "Reason for Access" field ...

Guide on implementing findOne for name validation in Node.js using data from MongoDB

Can someone help solve the issue of name duplication and provide guidance on how to execute the codes in Postman API? The attached codes can be found below: *employeemodel.js enter image description here *employeecontroller.js enter image description her ...

Bring your Electronic Catalogue to life with the addition of dynamic HTML content showcasing the latest

I am creating a digital magazine but I am facing the challenge of having to deal with 200 pages in jpg format. To streamline the process, I am looking for a way to use a combination of JavaScript and PHP to avoid manually coding for each of the 200 pages. ...

What is the best way to reach the end of a countdown and hit 0

Is there a way to complete the countdown to 0 second? Once the countdown is finished, it will display 00days00hours00minutes01seconds I would like it to show 0 seconds like this 00days00hours00minutes00seconds. Is there a method to achieve this? Explore ...

Mobile-responsive iFrame content is designed to adjust and fit appropriately on

While my iframe is responsive on both mobile and website, I am facing an issue where the content overflows (both overflow X and Y) from the width and height of the iFrame. Here's the scenario: in the mobile view (simulated using Google Chrome to mimi ...

Cookies store their values within the document.cookie framework

My cookie contains the following data: emailID=a1%40a.comSEPmaths=0SEPphysics=0SEPchemistry=0SEPbotany=0SEPzoology=0SEPta mil=0SEPenglish=0SEPpolity=0SEPgk=0SEPhistory=0 However, when I use document.cookie.split('; '), it returns the encoded ve ...

Challenges when utilizing AJAX and JQuery for selecting multiple items and retrieving data from a JSON file

I am currently working on a live search feature that extracts data from a JSON file using AJAX and jQuery. The goal is to make the fetched value clickable and populate a multiselect field with it. Once this is achieved, the plan is to capture the remaining ...

Trigger an immediate Primefaces update using a JavaScript function

Having an issue where: upon page load, I attach a 'keypress' event listener to every input field on the page. The goal is to check for special characters in the input and remove them. Below is the function that executes on page load: function ...

"A currency must be designated if there is a value present in a monetary field" - The default currency is established

I've encountered a major issue with one of my managed solutions. I have a customized workflow that generates multiple custom entities, each with various money fields. Here's the scenario when I trigger my workflow: The custom workflow enters a ...