A more efficient method for querying documents based on ids that are not in a given list and then sorting them by a specific publish date

After implementing the code provided below, I noticed that the performance tests indicate each request takes a second or longer to complete. My goal is to enhance this speed by at least 10 times. The bottleneck seems to be caused by the NOT operator resulting in a full scan of the data. Is there a more efficient way to execute the $not $in operation? Perhaps there is a different approach that can yield faster results. I experimented with using $lookup to join a temporary collection with the main one, but it turned out to be even slower as it involved creating a new collection, inserting data, running the $lookup query, and then deleting the temporary collection afterwards. I am curious if there is such a thing as a "negative" index that could improve performance.

const filter = {
         state: "Live",
         id: { $not: { $in: ids } },
         "type": "Message",
       };
const docs = await MyModel.find(filter, { _id: 0, __v: 0 })
         .sort({ "live_date": -1 })
         .lean();
}

Answer №1

First things first, make sure to analyze the query plan using the explain() function.

If the results are not satisfactory, perhaps try utilizing the hint() method to see if it provides any improvement.

In case you are running the most recent versions and the query optimizer seems to struggle with the $not : $in operation, it might be worth considering opening a jira ticket for further investigation?

Is the cardinality of your data such that using not in with an index actually enhances performance? Sometimes, filtering out a small percentage of items using an index does not significantly impact database performance.

Additionally, think about incorporating a limit clause into your query. Are you really interested in retrieving all results or just the first page? This can have a significant effect on query performance. In scenarios where $not : $in is expected to return most collection items, dealing with a large dataset could lead to potential bottlenecks?

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

I am encountering an issue with importing modules from the public folder in Next.js when using TypeScript, as I am

I've been running into an issue with importing files in Next.js using TypeScript. I'm trying to use regular imports with custom absolute paths, but I keep getting a module not found error. Oddly enough, my IDE is able to locate the file when I cl ...

The MongoDB NodeJS client fails to automatically reconnect to the Replica Set when the primary server goes offline

MongoClient.connect('mongodb://mongo1,mongo2,mongo3?replicaSet=rs', { useUnifiedTopology: true, }, (err, mongoClient) => { setTimeout(() => { mongoClient.db("mydb").collection('mycollection').insertOne({...}) } ...

Struggling to make comparisons with numerical data from MongoDB in an ExpressJS route

I am currently developing a website using Node.js, EJS template, MongoDB, and Express. I am working on implementing search functionality on my page using forms, but I am encountering a small issue. The problem is related to a logical issue in the search f ...

Describing an Object with some typed properties

Is there a method to specify only a portion of the object type, while allowing the rest to be of any type? The primary objective is to have support for intelliSense for the specified part, with the added bonus of type-checking support. To demonstrate, let& ...

Resetting the state back to its initial value - which one to use: useState or useReduce?

In order to enhance the functionality of a third-party Authentication service Auth0's useAuth0 hook, I have developed a custom hook called useAuth. This custom hook is responsible for managing local variables that store essential user information like ...

Updating a field in Mongoose by referencing an item from another field that is an array

I have developed an innovative Expense Tracker Application, where users can conveniently manage their expenses through a User Collection containing fields such as Name, Amount, Expenses Array, Incomes Array, and more. The application's database is p ...

Issue encountered while trying to connect to MongoDB: MongooseServerSelectionError

I am encountering an issue while attempting to establish a connection from my Node.js application to MongoDB using Mongoose. Every time I try to launch the application, I encounter the following error: "Error connecting to MongoDB: MongooseServerSele ...

Ways to import a library in JavaScript/TypeScript on a web browser?

I'm currently working on a project that involves a TypeScript file and an HTML page. Right now, I am loading the necessary libraries for the TypeScript file in the HTML Page using script tags like <script src="https://unpkg.com/<a href="/cd ...

Getting the version from package.json in Next.js can be easily achieved by accessing the `version

In my quest to retrieve the "version" from the package.json in a Next.js application, I encountered a roadblock. I attempted using process.env.npm_package_version, similar to how it is done in a Node application, but unfortunately, it returned undefined. ...

Struggling to locate documentation or a solution for this particular error encountered in MongoDB

{"ok":0,"code":4031700,"codeName":"Location4031700","name":"MongoError"}} Hey there, I've been trying to research this error, but I couldn't find any information about it. I checked th ...

Learn to update array fields within nested schemas in MongoDB and Node.js by gathering input directly from the user

Please refrain from providing solutions that do not meet the requirements. I have successfully implemented REST API methods such as GET, POST, PUT, and DELETE, but encountering issues with PATCH. Kindly assist in correcting this. The necessary code is atta ...

An error has occurred in NextJs: TypeError - Attempting to access a property that is undefined (reading '0')

I am facing an issue while trying to establish a connection with Mongodb in order to define the connect, disconnect functions and utilize them in an API. The error I encounter is a TypeError stating that it cannot read properties of undefined (reading &apo ...

Converting JavaScript code for Angular: A step-by-step guide

I have been working on integrating a feature similar to the one demonstrated in this Angular project: https://codepen.io/vincentorback/pen/NGXjda While the code compiles without any issues in VS code, I encountered two errors when attempting to preview it ...

Angular 5 offers the capability to use mat-slide-toggle to easily display and manipulate

I am experiencing an issue with displaying data in HTML using a mat-slide-toggle. The mat-slide-toggle works correctly, but the display does not reflect whether the value is 1 (checked) or 0 (unchecked). Can anyone provide some ideas on how to resolve this ...

Guide on utilizing a provider's variable in another provider within Ionic 2/3

In my code, I have a boolean variable called isConnection that is used to monitor network connection status. This variable is defined in a provider named 'network' and can be set to either true or false in different functions. Now, I need to acc ...

Leveraging CDK Context Variables in C# Lambda Initialization Code

I have a .NET Lambda function written in C# that is implemented as a .NET Minimal API according to the guidance provided here. To define AWS resources, I am utilizing CDK (TypeScript). Within my build pipeline, there is shell scripting involved to supply ...

The compatibility of return value types between the constructor signature and the call signature interface is not maintained when they are used together

I'm new to TypeScript and I'm struggling to figure out why I'm getting a type error in the code below. Can someone help me identify what's wrong? interface CallOrConstruct { new (value: string): Person (value: number): number } cla ...

Do const generics similar to Rust exist in TypeScript?

Within TypeScript, literals are considered types. By implementing const-generics, I would have the ability to utilize the value of the literal within the type it belongs to. For example: class PreciseCurrency<const EXCHANGE_RATE: number> { amount ...

Creating dynamic Kafka topic names within a NestJS microservice

Currently in Nestjs, I have integrated Kafka as my message broker and specified the topic name like so: @MessagePattern('topic-name') async getNewRequest(@Payload() message: any): Promise<void> { // my implementation logic } I am curious ...

Express string declaration in a single TypeScript line

const restrictString = (str: string): string => str.match(/[ab]/g)?.join('') || '' Is there a way to restrict a string to only contain the characters 'a' and 'b' in a one-liner function? I am aware that this can ...