Issue with executing nested iteration through cursors in MongoDB shell

When faced with two nested cursor.forEach() functions or a while loop, the second one doesn't seem to be executed. The issue arises when attempting to remove duplicates from a vast collection by transferring documents to another collection and checking for existing duplicates using the following code in the mongo shell:

var fromColl = db.from.find(),
    toColl;

fromColl.forEach(function(fromObj){
    toColl = db.to.find({name: fromObj.name});
    if (toColl.length() == 0) {
        //no duplicates found in the target collection, insert
        db.to.insert(fromObj);
    } else {
        //possible duplicates found in the target collection
        print('possible duplicates: ' + toColl.length());
        toColl.forEach(function(toObj){
            if (equal(fromObj.data, toObj.data)) {
                //duplicate...
            }
        });
    }
});

Although toColl.length() is printed in the else block, the second forEach loop fails to execute. Any idea why this might be happening?

Answer №1

--- ALTERNATIVE SOLUTION ---

After some experimentation, I devised a workaround by creating an array of the second cursor like so:

toColl = db.to.find({name: fromObj.name}).toArray();
. I then proceeded to iterate through this array using a basic JavaScript for loop:

var fromColl = db.from.find(),
    toColl,
    toObj;

fromColl.forEach(function(fromObj){
    toColl = db.to.find({name: fromObj.name}).toArray();
    if (toColl.length == 0) {
        // No duplicates found in the target collection, insert
        db.to.insert(fromObj);
    } else {
        // Possible duplicates found in the target collection
        print('Possible duplicates: ' + toColl.length());
        for (var i = 0; i < toColl.length; i++) {
            toObj = toColl[i];
            if (equal(fromObj.data, toObj.data)) {
                // Duplicate...
            }
        });
    }
});

--- UPDATE ---

In light of feedback from Stephen Steneker:

The mongo shell offers shortcuts for data manipulation within the shell environment. More information on these shortcuts can be found in the MongoDB documentation: Iterating Through a Cursor in MongoDB Shell.

One key point highlighted is that when the returned cursor isn't assigned to a variable using the var keyword, it automatically iterates up to 20 times to display the first 20 documents in the results.

In the provided code sample, the declaration of toColl with var preceded the execution of find().

Although iterating all results with toArray() is an option, it necessitates loading all cursor documents into memory. Manually iterating over the cursor is deemed a more scalable approach.

-- RESOLUTION --

A critical issue arose due to using toColl.length() instead of toColl.count().

This was because toColl.length() causes the cursor to reset.

Special thanks to Rhys Campbell and Stephen Steneker from the MongoDB user group for their valuable assistance in resolving this setback.

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

Learn how to easily incorporate a drop-down list into the material-UI Search component within the navbar to enhance the search results

I integrated a Material UI search bar into my React app's navbar following the instructions from the official documentation on MUI. However, the article does not provide any guidance on how to add a dropdown list when selecting the search input field. ...

Can WebDriverJS be compiled without code minimization using Google Closure Compiler?

I am in need of customizing WebDriverJS to suit my specific requirements. However, I am encountering difficulties with debugging the compiled source code. Having descriptive function names and comments would greatly assist me! Therefore, I am curious to kn ...

Tips for locating 2 geopoints in mongodb with the help of mongoose

Currently, I am working on a project that uses NodeJS with the Mongoose driver for the backend and MongoDB as the database, along with Angular 6 for the front end. One of the requirements is implementing a feature to search for data using two geoPoints. Ho ...

What is the best way to serialize the file from a form for uploading and storing in a MongoDB database, utilizing Backbone.js, jQuery, and Node.js?

I'm currently working on implementing a file uploader feature that allows applicants to upload their resumes for specific job posts. I've managed to capture all the form values except for the file upload input. How can I successfully upload, seri ...

Promise not resolving when image onload event is not being triggered

Hello, I've encountered an issue while working with a promise and recursion within a loop. The problem is that the onload event never triggers, causing the promise not to resolve as expected. Could someone please review my code and point out any mist ...

How to create a karma-jasmine test case in Angular 2 to trigger a modal opening when a link is clicked

I need to verify that when a link is clicked, a modal should open. In my spec.ts file, I have written the following test: describe('NavbarComponent', () => { let comp: NavbarComponent; let fixture: ComponentFixture<NavbarComponent& ...

Having trouble with PHP Storm and Vue component not working? Or encountering issues with unresolved function or method in your

I have been struggling with this issue for days and cannot seem to find a solution online. Being new to Vue.js, I am currently working on a TDD Laravel project: My goal is to add the standard Vue example-component to my app.blade.php as follows: app.bla ...

The mark-compacts were not efficient enough, they approached the heap limit and as a result, the allocation failed. The JavaScript

Currently working with Angular version 7.2 and encountering an issue when running ng serve: FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory What does this error mean? How can it be resolved? The ...

Using Javascript or Typescript constants along with WebPack being invoked twice

I am encountering an issue with my constants file: collections.ts import {Mongo} from 'meteor/mongo'; import {Chat, Message} from 'api/models'; export const Chats = new Mongo.Collection<Chat>('chats'); export const Me ...

Employing the identical directive within a directive [angularjs]

My requirement is to utilize the same directive within another directive, based on a conditional parameter. However, every time I attempt to do this, it appears to enter an infinite loop. It seems like the templates are being preloaded and causing a recurs ...

The behavior of the Ionic checkbox in version 5 seems to be quite delayed

I am facing an issue with binding the checked attribute value on an ion-checkbox, as the behavior seems to be delayed. In my .ts file, I have an array variable named user_id. In my checkbox list, I am trying to populate this array based on which checkboxe ...

How to Insert Key-Value Pairs into CKEditor Selection Element

According to the documentation, to include a select element with distinct keys and values, you can follow this format: { id: 'my-element-id', type: 'select', label: 'My element', items: [ { value: &ap ...

Find the mean of two fields by taking into account the entries from the previous 5 minutes on the specified datetime in MongoDB

Utilizing a sensor, I am gathering data on humidity and temperature, with the sensor providing data every minute. Below is a sample of the collected data: /* 1 */ { "temperature" : 30.80, "humidity" : 77.90, "acquisitio ...

Vue's beforeRouteEnter hook patiently awaits for the child component to complete its request

My Vue app utilizes beforeRouteEnter to load data and prevent the undesirable "flash of unloaded content." Loading data on some pages is straightforward: async beforeRouteEnter(to, from, next) { const newestPosts = await getNewestPosts(); next(vm ...

Setting up multiple base tags in AngularJS for different modules

When working with angularjs, there is a "#" that needs to be removed. This can be achieved by setting: $locationProvider.html5Mode(true); Additionally, adding the base tag ensures normal functionality when the page refreshes. If <base href="http://exa ...

Encountering a type error while trying to create a document within a nested collection in Firebase Firestore

While trying to submit the form with property data, I encountered an error message: FirebaseError: Expected type 'za', but it was: a custom Ha object. There doesn't seem to be any information available online explaining what a Ha object is o ...

What is the best way to send HTML content from a controller using ajax?

Here is the code in my controller: public async Task<ActionResult> GetHtml(int id) { var myModel = await db.Models.FindAsync(id); return Json(new { jsonData = myModel.MyHtml }, JsonRequestBehavior.AllowGet); } This is ...

using angular.js to assign a value to an <input> field

There seems to be an issue with the code, as I am unable to see the value in the HTML: '<div ng-app="BusinessinfoModule" ng-controller="BusinessinfoController" <label>Your Business Name</label> <input ...

Customizing response headers in vanilla Node.js

My Node.js setup involves the following flow: Client --> Node.js --> External Rest API The reverse response flow is required. To meet this requirement, I am tasked with capturing response headers from the External Rest API and appending them to Nod ...

Retrieve all items pertaining to a specific week in the calendar

I'm trying to obtain a list of week ranges for all data in my MongoDB. When a week range is clicked, only the records for that specific week range should be displayed. By clicking on the week range, the ID of the week (let's say 42, representing ...