What is the most efficient way to transfer a large volume of documents from mongoDB using http?

I'm dealing with a large mongoDB database that contains millions of documents and I need to fetch them all at once without crashing or encountering cursor errors. My goal is to send this data over http using express in nodeJS. The collection contains thousands of documents, each with a field containing thousands of smaller documents. Currently, the size of my collection is 500MB. Do you have any recommendations for handling this big data scenario? Should I consider implementing a limit/skip based solution? If so, could you provide an example code snippet?

I've already tried document streaming, which appeared more reliable, but I still encountered the same cursor issue (Cursor not found).

app.get("/api/:collection", (req, res) => {
    const filter = JSON.parse(req.query["filter"] || "{}");
    const projection = JSON.parse(req.query["projection"] || "{}");
    const sort = JSON.parse(req.query["sort"] || "{}");

    db.collection(req.params.collection).find(filter)
        .project(projection).sort(sort)
        .stream({ transform: JSON.stringify })
        .addCursorFlag("noCursorTimeout", true)
        .pipe(res); 
});

Answer №1

It's recommended to compress your response using gzip.

To implement compression, you can use the following npm command:

npm i --save compression

Then include the following code in your Express application:


var compression = require('compression');  
var express = require('express');  
var app = express();  
app.use(compression());

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

Updating the text of a Mat-Label dynamically without the need to reload the page

In my application, there is a mat-label that shows the Customer End Date. The end date is fetched initially through a GET request to an API. Let's say the end date is 16-05-2099, which is displayed as it is. There is also a delete button implemented f ...

What could be causing Node Mailer to struggle with sending emails on a private host when it performs perfectly on localhost and render?

I am encountering an issue with sending emails to my clients using nodemailer. I am on a shared hosting with cpanel and it is not able to send emails, whereas it works fine on other hosts. Below is the function responsible for sending emails in my code: c ...

When using `element.addEventListener`, event.target will be the target

When working on a solution, I initially bound event listeners to multiple targets within the same container. I am curious to know if anyone has noticed considerable performance improvements by using just one event listener and leveraging the target of the ...

Struggling to create an access token with the Slack API

My goal is to retrieve an access token from the Slack API. When I use the code provided below, it generates an authorization URL containing a temporary code in the query string. Once permissions are granted, the process redirects to /slack/oauthcallback. ...

In Chrome, there is a conflict between the screen width when using `position: absolute` and `position: fixed` if there is vertical

I'm in the process of developing a website with a video banner set to fixed positioning in the background, and a div that has absolute positioning covering part of the video on the bottom half. However, I've encountered an issue - when I add this ...

Incorporate the jquery lazy load plugin alongside ZURB foundation data-interchange for optimal performance

Currently, I am engaged in a project that involves utilizing the ZURB foundation framework alongside its data-interchange feature to display various images based on different screen sizes. To learn more about this method, please visit: You can also explo ...

Extracting Query Parameters from a Successful Ajax Call in Javascript

How can I extract data from the success response? Take a look at my code snippet: $.ajax({ async: 'true', url: 'https://exampleapi.com/product', type: 'GET', data: {page: idQuery}, success:(response => { v ...

When is it appropriate to use app.use compared to when should app.all be used?

Within the documentation of express, there is an example that showcases the following: app.use('/user/:id', function (req, res, next) { console.log('Request Type:', req.method) next() }) This situation can be somewhat puzzling sin ...

Retrieve data from MongoDB collection using various criteria

From a given mongo document stored in a collection: { "_id":"ObjectId", "value":{ "id": 1, "payment": [ { "status": { "id": "1.1", "value": "Paid" } }, { "status": { ...

A method for arranging an array of nested objects based on the objects' names

Recently, I received a complex object from an API: let curr = { "base_currency_code": "EUR", "base_currency_name": "Euro", "amount": "10.0000", "updated_date": "2024 ...

The server side is experiencing an issue when attempting to send an update request to update a profile,

My current challenge involves sending an axios put request to update profile details while dealing with a non-editable email field. How can I include the email id along with the Axios.put(…) request in this scenario? Upon setting a breakpoint on the ser ...

AngularJS allows for the passing of a function value into another function

Is there a way for me to pass a value from one function to another? Here is an example of what I am trying to achieve: HTML <div> <li ng-repeat="language in languages" ng-click="myFirstFunction(firstValue) {{lang ...

The power of Angular controllers lies in their ability to facilitate two-way

Currently, I have a controller that acts as a wrapper for ui-router and manages its flow, similar to a menu bar. When a user clicks on a menu item, a function is triggered that changes the ui-router state and broadcasts an event to the inner controllers. E ...

Unable to render images in Angular client due to issues with accessing upload path in Express Node.js backend

I've been struggling with the issue of displaying images on the Angular client for a while now, despite going through numerous similar questions. The files are successfully uploaded to the upload folder and their details are stored in the MongoDB data ...

Page elements subtly move when reloading in Chrome

I am experiencing an issue with a div that has left and top offsets randomly selected from an array of values upon page load. Most of the time, it works fine. However, occasionally, upon refreshing the page, the window scrolls down slightly, revealing the ...

The pagination in Laravel Vue is causing a validation error due to an invalid prop type check failing

Recently, I delved into working with Nuxt.js and decided to install the Laravel-Vue-Pagination plugin. However, I encountered an error message in my console system that reads: [Vue warn]: Invalid prop: type check failed for prop "data". Expected Object, ...

Chaining Requests with ExpressJS

Looking to create a specific process in expressejs where I have two endpoints and need to pass the result of the first endpoint to the second one. Here's an approach based on a guide: var cb0 = function (req, res, next) { console.log('CB0&apos ...

Ways to perform a redirect following data retrieval from a post request

I am working on a post method for a servlet, where the servlet returns a web page after forwarding a request to another page. Instead of directly redirecting using window.location = "/AnotherServlet", I have tried various solutions including passing parame ...

"Encountered an issue with Socket.io loading on the client side, but it functions properly

I'm having trouble with my Express/Node/PeerJs application that utilizes socket.io. It runs fine in localhost but encounters issues when deployed to Heroku or Nodejitsu. Here is a snippet from my app.js: var routes = require('./routes'); v ...

What is the method used by three.js to render video with spherical UV mapping?

I have a streaming video displayed in a 3*3 format. I am able to splice the entire video into individual sections using THREE, // Creating a 3x3 PlaneGeometry var geometry = new THREE.PlaneGeometry(400, 200, 3, 3); const video1 = document.getElem ...