Using MongoDB to efficiently paginate results

Currently engaged in the development of a web application using MongoDB, which dynamically populates pages with content on the browser.

Familiar with two different methods for paging (referenced here: ):

1) Utilizing .skip() + .limit()

2) Implementing

.find({_id > last_id}).limit(n)

Acknowledging the performance challenges associated with the first approach, it was immediately ruled out.

The second method proves to be effective but only when results are sorted by the _id field. Sorting by a non-unique field like Date might exclude some documents due to potential duplicates.

In addition, users must navigate through pages sequentially as a variable such as last_id needs continuous updating based on the _id of the final document on the previous page. Skipping from page 1 to 7 might lead to page 7 displaying results meant for page 2 because the last_id retains the _id value from the last item on page 1.

Hence, the query remains - how can one execute paging when sorting by a non-unique column (e.g., Date or firstName) and facilitate users' ability to jump multiple pages simultaneously?

Any suggestions would be highly valued and appreciated. Thank you!

Answer №1

The advice provided is accurate - it's safe to skip unless you anticipate dealing with a large volume of documents. However, in the event that your application unexpectedly gains immense popularity, it's crucial to ensure that your code remains robust and doesn't break under high user loads.

If you opt to sort by date and then by ID, you can implement the following query:

.find(
  {
    date:{
      $lte:lastDate
    },
    _id:{ 
      $lt: lastId 
    }
  }
).limit(n)

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

assigning individual IDs to buttons within an array

Looking for assistance with my school project, which involves creating a booking system for a cinema. I have used an array to generate the chairs but am unsure how to assign each button its own ID. Here is the code snippet in question: function chair(){ ...

Testing NestJS Global ModulesExplore how to efficiently use NestJS global

Is it possible to seamlessly include all @Global modules into a TestModule without the need to manually import them like in the main application? Until now, I've had to remember to add each global module to the list of imports for my test: await Tes ...

Tips for delaying the evaluation of an <input> field?

I am interested in analyzing the content of an <input> field when there is no activity from the user. One simple example I have considered is counting the number of characters, but the actual analysis process is very resource-intensive. To optimize ...

Is it possible to embed an Angular application within a specific DOM element?

I am the proud owner of two web applications. One is a traditional JavaScript web app, while the other is built on Angular (Version 10). My goal is to load the Angular app inside a DIV container after the JavaScript app has finished load ...

Utilizing Google Analytics 4 in a React TypeScript Environment

Currently, there are two options available: Universal Analytics and Google Analytics 4. The reasons why I lean towards using Google Analytics 4: Universal Analytics is set to be retired on July 1, 2023, so it makes sense to start fresh with Google Analyt ...

Angular unable to send object to HTML page

Struggling with learning angular, encountering new challenges when working with objects in different components. In two separate instances, try to implement two different mechanisms (microservice or service component serving an object directly). This speci ...

Tips for developing a nested array of objects using a JavaScript loop

Can someone help me with looping an AJAX response to create an array in this format? "2023-03-30": {"number": '', "url": ""}, "2023-03-30": {"number": '', "url": &quo ...

Updating parent model with select list value using a directive

Seeking help with a directive that produces a select list. I'm trying to pass in the id and value keys of the object for reusability. However, the list isn't binding to its parent model when it's updated. Any ideas on why this might be happe ...

Closing menu smoothly with CSS or JavaScript transition

I've set up a sidebar div and a content div to function as two CSS grid columns. The sidebar itself consists of two additional columns, but here's the basic structure: <div class='site-wrap'> <div class='sidebar' ...

What causes multidimensional lists to flatten when a large dictionary is passed from Python to Julia?

Currently, I am developing a python client for a coding game that was originally created in javascript. The game utilizes a json object of game data which can be found at . Within this data structure, each map includes a list of doors with various attribut ...

What could be the reason for my http request failing to receive a response?

I have successfully implemented multiple routes in my API, but I am encountering issues with the comment system. I am not receiving any response when accessing the URL (node backend) or using Postman. While my server JS code works for POST requests, teams ...

Getting latitude and longitude from Google Maps in a React Native appHere are the steps to

Looking to retrieve the latitude and longitude from Google using React Native. As a newcomer to React Native, I have been unable to find any resources to address this issue. Any assistance would be greatly appreciated. Thanks! Thanks ...

Using the React API to fetch data

Just starting out with React and APIs, I decided to fetch data from a MongoDB API. The data is being logged correctly in the console, but I'm having trouble rendering it. import React from 'react'; class Api extends React.Component { comp ...

The click function is not functioning properly when trying to integrate a jQuery Ajax HTTP request

Here is my query: I am trying to make an Ajax request from within a click function using jQuery (as shown in the example below). However, no data is being retrieved even though I am alerting it through the success function. Could you please guide me on wh ...

What steps must be taken to establish a universal connection to MongoDB that can be shared across multiple files?

Currently, I have my main server file named index.js: const express = require('express') const app = express() const route = require('./route') app.use('/main', route) app.listen(3000) Additionally, there is the route.js f ...

Issues encountered while trying to access a child state using Ionic and UI-Router

My current setup includes the following parent states: // Abstract state for tabs directive .state('tab', { url: "/tab", abstract: true, templateUrl: "templates/tabs.html", controller: "TabCtrl" }) // Each tab has its ow ...

An error occurred while using $http.jsonp: unexpected character '<'

Even though I am receiving a response from the request, the .then() section of my code does not seem to be triggering. Can you help me figure out what mistake I might be making? window.distance24Result = function(data){ alert(data.distance); }; $http.js ...

Steps to manage the time delay between mousewheel events triggering

Currently, I am working on a website for a movie production company that showcases their various films in full-screen mode. Each video is listed and there is a function that automatically takes the user to the next video when a mousewheel event occurs. How ...

Concern regarding the duration setting in the date-picker

Is there a specific "campaign duration" rule where you must select a date between the first and last day of the month? If you choose a date outside of this range, such as a date from the next month, the Backend API will return an "Input param error." Curr ...

Developing a nested data table using Angular and mongoose framework

I'm struggling to display the contents of a nested array field within a mat-table. Below is the code I currently have (stored in employee.component.ts): employee: Employee; usages: Usage[]; dataSource: MatTableDataSource<Usage>; displ ...