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

React: The useContext hook does not accurately reflect the current state

I'm currently facing a dilemma as I attempt to unify data in my app. Whenever I click the button, the isDisplay value is supposed to be set to true; even though the state changes in my context file, it does not reflect in the app. Thank you for your ...

"encountered net::ERR_NAME_NOT_RESOLVED error when trying to upload image to s3 storage

I am currently developing an application using Angular. I have been attempting to upload a picture to my S3 bucket, but each time I try, I encounter this error in the console. https://i.stack.imgur.com/qn3AD.png Below is the code snippet from my upload.s ...

How do I disable split panel on Ionic 2 login page exclusively?

I have successfully implemented the split-pane feature in my app.html file. However, I am facing an issue where the split pane is being applied to every page such as login and SignUp. Can someone please guide me on how to restrict the split pane function ...

I am struggling to make the map method display the specific components I need

Attempting to create a scalable Custom Form using an array of objects and a custom Input field in a React-Typescript project import React, { ChangeEvent } from "react" import { InputField } from "./InputField" interface FormItem { ...

Ways to avoid Next.js from creating a singleton class/object multiple times

I developed a unique analytics tool that looks like this: class Analytics { data: Record<string, IData>; constructor() { this.data = {}; } setPaths(identifier: string) { if (!this.data[identifier]) this.da ...

Automate the compilation of Typescript project references by creating a solution that allows for passing unique options to each

When compiling or building a project with references programmatically, I make use of the ts.createSolutionBuilder API. The challenge I face is that in my specific scenario, I do not have individual tsconfig.json files stored on the filesystem for each pac ...

Unleash the full power of Angular Components by enhancing them with injected

I am facing a challenge with handling the destruction event of an Angular component in my external module that provides a decorating function. I've run into issues trying to override the ngOnDestroy() method when it includes references to injected ser ...

Removing one element from an array with mongoose

As a newcomer to web development, I am currently working on creating a todo app. Below is the schema and model that I have: const tdSchema = new mongoose.Schema({ category: { type: String, required: true, unique: true }, tds: { type: ...

Tips for uploading a file and submitting form data with Angular2, using [(ngModel)], and then storing the reference in MongoDB

Currently, I am working on a task page and I need to implement the functionality to upload a file along with the form submission to the NodeJs express server. @Component({ selector: 'tasks', template: `<div mdl class="mdl-grid demo-c ...

How to enhance an existing JSON object by including a new attribute in a Node.js environment

Here is an object that I am working with: ==================records=========={ Id: 5114a3c21203e0d811000088, userId: 'test', sUserId: test, userName: 'test', url: 'test', Title: 'test' } I am trying to ad ...

Maximizing the potential of NestJS apps with Docker

I am working on a NestJS project that consists of multiple apps structured as follows: my-project: -- apps; --- app-one ---- src ---- tsconfig.app.json --- app-two ---- src ---- tsconfig.app.json -- libs -- package.json -- etc... Within this project, I ha ...

Converting retrieved data into table cells through mapping

I'm facing an issue where I need to display specific addresses for each individual in a table row. For simplicity, let's focus on showing the city specifically as described in this code snippet: https://i.stack.imgur.com/bJmsD.png Currently, whe ...

Guidelines for segregating a Union from an Array

I'm currently utilizing graphql-code-generator to automatically generate TypeScript definitions from my GraphQL queries. I have a specific union within an array that I am trying to extract in TypeScript. Is this feasible? Although I came across an exa ...

The AOT Compilation error occurs in Angular2 RC6 when trying to call the function RouterModule.forChild(ROUTES) which is not supported

Operating Environment: Windows 10, IntelliJ 2016.2, node Angular Version: 2.0.0-rc.6 Language: [all | TypeScript X.X | ES6/7 | ES5] Typescript ES6 Node (for Ahead of Time Compilation issues): node --version = Node 4.4.7, NPM 3.10.6 The AOT com ...

Type Error TS2322: Cannot assign type 'Object[]' to type '[Object]'

I'm facing an issue with a code snippet that looks like this: export class TagCloud { tags: [Tag]; locations: [Location]; constructor() { this.tags = new Array<Tag>(); this.locations = new Array<Location>(); ...

What are the steps to defining a static constant within a TypeScript class?

What is the best way to define a TypeScript static constant within a class so that it can be accessed without initializing the class instance? Below is an example of my class structure: export class CallTree{ public static readonly active = 1; .. ...

Angular 6: Exploring the Challenges of Extending Services Without Sacrificing the Functionality of ChildService

As I was developing multiple angular REST-services for my frontend, I came up with the idea of creating a base class BaseRestService to handle common functionalities like headers and helper functions. However, I encountered TypeErrors when trying to call ...

In Angular 16, allow only the row that corresponds to the clicked EDIT button to remain enabled, while disabling

Exploring Angular and seeking guidance on a specific task. I currently have a table structured like this: https://i.stack.imgur.com/0u5GX.png This code is used to populate the table: <tbody> <tr *ngFor="let cus of customers;" [ngClass ...

What is the best way to create a dynamic sitemap in Next.js version 14?

I've encountered an issue with the code snippet I'm using for a dynamic sitemap on my blog post website built with Next.js 14. While it works perfectly fine in development, it fails to generate a dynamic sitemap in the build or production environ ...

Guide to updating nested documents in MongoDB using Mongoose, Express, and NodeJS

Looking at my Mongoose Model named Profile: const mongoose = require("mongoose"); const Schema = mongoose.Schema; const ProfileSchema = new Schema({ ... }); module.exports = Profile = mongoose.model("profile", ProfileSchema); Within this model, I h ...