What is the best way to loop through a MongoDB collection using mongojs?

In my current project, I am utilizing the mongojs library and facing an issue while attempting to iterate through all elements in a collection.

index = 0

db.keys.find({}, {uid: 1, _id: 0}).forEach((err, key) =>
    if err?
        console.log err
    else 
        console.log (++index) + " key: " + key_uid

This code snippet logs:

1 key: bB0KN
2 key: LOtOL
3 key: 51xJM
4 key: x9wFP
5 key: hcJKP
6 key: QZxnE
.
.
.
96 key: EeW6E
97 key: wqfmM
98 key: LIGHK
99 key: bjWTI
100 key: 2zNGE
101 key: F71mL

However, the logging stops prematurely. Upon checking from the terminal using MongoDB, the command

> db.keys.count()
2317381

reveals that there are significantly more keys in the database that should be returned. Any suggestions on what might be causing this unexpected behavior?

Answer №1

It is important to utilize the each() method instead of forEach(). When using forEach(), it will iterate over every document in the batch, which defaults to 101. With each(), it will iterate over each document in the cursor directly. Referencing the documentation:

each

This method iterates through all the documents within the cursor. Similar to {cursor.toArray} not all elements will be processed if this cursor has already been accessed. If that's the case, {cursor.rewind} can be utilized to reset the cursor. Unlike {cursor.toArray}, this method only holds a maximum of batch size elements at one time when the batch size is specified. If not, it is up to the caller to ensure that the entire result fits into memory.

http://mongodb.github.io/node-mongodb-native/api-generated/cursor.html

Sample code snippet:

// Obtain a cursor
      var cursor = collection.find();

      // Use the each method, triggers for every document
      cursor.each(function(err, item) {

        // If item is null, then the cursor is empty and closed                  
        if(item == null) {

          // Indicate that the cursor is now closed
          cursor.toArray(function(err, items) {
            assert.ok(err != null);

            // Close the database connection
            db.close();
          });
        };
      });

Answer №2

The reason you are only able to see the first 101 documents is because that is the default number of documents that the MongoDB driver retrieves from the server in the initial batch.

Typically, the first batch will bring back 101 documents or enough documents to exceed a size of 1 megabyte. Subsequent batches are set at 4 megabytes each.

If you want to view more documents, you can use the find method and then loop through each document.

coll.find({}, {uid:1, _id : 0}, function(err, docs){
    if (err) {
        console.log(err);
        return;
    }
    docs.forEach(function(doc, index) { 
        console.log(index + " key: " + doc.uid) 
    });
});

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

The automated linting process through npm script did not meet the desired expectations

I need help setting up a script that will automatically fix all files in my Vue project like this: "lint": "eslint --fix vue/**/*.vue && eslint --fix vue/**/*.js" The goal is to automatically lint all .vue and .js files within the project. Unfor ...

How can I compare equal values and determine whether they are true or false using MongoDB aggregation?

This is a simple like and dislike system. I am trying to determine if the user has liked the post or not. This is what I have accomplished so far, but I am encountering an issue where I get false when using ids instead of variables. When using variables, i ...

Troubleshooting "jest + enzyme + react16: The src attribute of <img> tag is not sending

Currently, I am utilizing jest along with enzyme for testing my react component titled "AnimateImage". This component includes an image element within it: import * as React from 'react'; import { PureComponent } from 'react'; interfac ...

Using ReactJS to strip HTML tags from JSON response

I'm having trouble figuring out how to strip HTML tags from a JSON response in reactjs. Here's the JSON response: { "price": "26,800.98", "diff": "<!--daily_changing-->+13.44 (+0.05%)&nbsp;& ...

Make sure that the click event listener is set up on the anchor element so that it also affects its children

Currently, I have implemented a click event listener on my anchor elements. However, the anchors contain a span element within them, and the event listener does not function properly if you click on the span inside the anchor. document.addEventListene ...

How to use jQuery to hide radio buttons that are not checked when clicking a submit

Looking to dynamically hide all unchecked radio buttons and their labels until a submit button is clicked, displaying only the checked radio button. <form method="post"> <input type="radio" name="radiobtn"> <label for="first">Fir ...

What is the best way to compare the values in a MongoDB array collection with an array of IDs?

My task involved a list of employee IDs stored in an array Employees Array let employeeIds= [ ObjectId("5b0d4c5ec47e6223a08af5fd"), ObjectId("5b1625f762368179e1e4549c"), ObjectId("5b3a15979a68763230202dfd"), ObjectId("5b3b0ea9074f944699f1 ...

The function Model.find({}) is coming back as empty despite the fact that there are records present in the

While I can successfully add data to the users collection using my '/sign-up' route, I'm facing an issue with reading all the documents from the users collection. Instead of the expected data, all I receive is an empty array. { "status": ...

Connect the B-Button to an input file using BootstrapVue

I am attempting to create an input file button within a v-for loop without using the b-form-file tag. Despite trying various solutions, none of them have worked for me. Here is the code I have so far: <b-button @click="selectFile()" variant=& ...

Transfer a single property from a particular object in one array to another array of objects based on a condition (JavaScript ES6)

I have 2 sets of data arrays coming from 2 separate API calls const data1 = [ { name: 'John', age: 30, id: 1, }, { name: 'Sarah', age: 28, id: 2, }, ]; const data2 = [ { status: 'active', ...

Can Ajax be utilized to call a PHP script that contains another Ajax function?

I have set up a checkbox that triggers an Ajax call to another PHP script once checked. In this PHP script, there are three text boxes and a button. When the button is pressed, another Ajax call is made to execute yet another PHP script, all within the sam ...

Maintaining the proportions of images in different screen sizes when resizing

I apologize if this question has already been addressed, but I have been unable to find a solution that works for my specific issue. My Gallery consists of a side list of available images in one section, which when clicked changes the image source in anot ...

AngularJS postback method fails to trigger

Seeking assistance with my angularJS AJAX postback method. Below is the HTML code I have created: <html xmlns="http://www.w3.org/1999/xhtml" ng-app> <head runat="server"> <title></title> <script src="Scripts/angular.js ...

Flask does not provide a direct boolean value for checkboxes

After struggling for a week, I am still lost on where to make changes in my code. I need the checkbox to return a boolean value in my Flask application. Below are snippets of the relevant code: mycode.py import os, sqlite3 from flask import Flask, flash ...

The Star Rating System fails to update accurately after hiding the Radio Buttons

I followed a tutorial to set up a Star Rating System Everything was working fine on the SHOW PAGE and the INDEX PAGE until I decided to hide the Radio Buttons and use the corresponding labels to submit the value. I encountered an issue where the JavaScrip ...

Placing a v-model within a Vue.js component

I am attempting to achieve something similar to this specific scenario, but I am struggling to find the appropriate technical terminology to describe it. Unfortunately, I haven't been able to locate a solution for this issue. <div id="app"> ...

Trigger an event, pause, and subsequently trigger another one within Vue

I have successfully emitted the following events to the parent component: this.$emit('sendToParent1', true); this.$emit('sendToParent2'); this.$emit('sendToParent3'); this.$emit('sendToParent4', true); this.$emit(&ap ...

What is the best way to handle multiple responses in Ajax within a single function?

Here is a simple code snippet: $.ajax({ url:'action.php', method: 'POST', data:{getcart:1}, success:function(response){ $('#getcart').html(response);//want to ...

Why does JSON.parse need to be run twice - once for a string and once for an object?

When I send a JSON string via websocket (Socket.io) from a Node.js server to a client's browser, I find that I have to execute the JSON.parse function twice in order to extract an object from the received JSON string. This behavior is confusing to me. ...

Tips for integrating CSS with Material UI TableContainer

I have utilized Material UI Grid to display data in a chart. However, the appearance of the chart does not match my expectations. Instead of resembling the desired "dense table," it looks different: Actual Look of the Chart Below is the code snippet I ha ...