Unexpected behavior with MongoDb $filter when using $or

Please click on this link to access the interactive coding playground and code along with me: playground

I have a collection called Pages where each document contains keys Urls and DraftUrls, which are represented as an array of objects listed below:


IncomingUrl: string;
EclipseId: string;
Status: string;
RedirectionLink: string;
Validity: Date;
Config: ConfigData[];
Indexing: boolean;

Now, my objective is to determine the number of URLs that either have an Inactive status or have an expired Validity date. Additionally, I need to extract additional information such as GroupName and TemplateName.

I attempted to utilize $filter with $or as demonstrated in the playground example, but encountered an issue where it returned the total count of all URLs without considering the specified conditions within the query.

Initially, I suspected a problem with how the Validity field was being evaluated. However, even after removing that condition and focusing solely on the Inactive state, the result still displayed the count of all URLs instead of filtering based on the desired criteria.

Answer №1

There seems to be an issue with your cond expression within the $filter. It needs to be adjusted so that the $filter operator is structured as follows:

{
    $addFields: {
      filteredUrls: {
        $filter: {
          input: isDraftB ? '$DraftUrls' : '$Urls',
          cond: {
            $or: [
              {
                $eq: [
                  "$$this.Status",
                  "Inactive"
                ]
              },
              {
                $and: [
                  {
                    $eq: [
                      "$$this.Status",
                      "Validity"
                    ]
                  },
                  {
                    $gte: [
                      "$$this.Validity",
                      currentDate
                    ]
                  }
                ]
              }
            ]
          }
        }
      }
    }
  },

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

When you assign the page results from the scrape-it npm to a variable, it will return a Promise with the status of "pending."

I recently downloaded scrape-it from NPM as a dependency and I'm trying to store the results in a variable instead of using a callback function. When I run the code snippet provided in the scrape-it documentation: var myVar = scrapeIt("http://ionicab ...

How can you sustain a backend connection using NodeJS as users navigate through different pages?

Currently, I am establishing connections through thrift (node-thrift) with a backend server for api calls. The communication is bidirectional (push/pull) to NodeJS. As users navigate various URLs and Node serves jade templates and javascript files using C ...

The viewport width in NextJS does not extend across the entire screen on mobile devices

I'm currently tackling a challenge with my NextJS Website project. It's the first time this issue has arisen for me. Typically, I set the body width to 100% or 100vw and everything works smoothly. However, upon switching to a mobile device, I not ...

Error arises when trying to use jspdf.addHTML

When attempting to use jsPDF in Angular 2, I encountered an issue while running the following code on a button click event: generatePDF(){ const options = {'pagesplit': true} this.pdf.addHTML(this.id.nativeElement, 10, 10, options, funct ...

ajax receives an empty responseText after sending intermediate data to Python on the backend

Initially, the frontend passed an identification to the backend. The backend utilized this identification to retrieve data from the database. The extracted data then underwent additional processing on the backend before being sent back to the frontend. Be ...

Obtain the session value in React

Currently, I am working on a React app along with a server-side application. I have successfully created a user session on the server side and now I want to retrieve its value in my React app. Can someone guide me on how to achieve this? const [user,setUse ...

Submitting a form in React/Javascript: A step-by-step guide

I have a website on Wordpress where I am using the Wp-Polls plugin to vote. How can I submit a post request by accessing a form URL in a React project? Specifically, how can I vote for the "Bad" option with a value of 2? The HTML structure of the WordPre ...

Using $scope.$on name parameter as an attribute within an AngularJS directive

My goal is to create a directive that allows me to pass in an attribute string, which will then be used as the "name" parameter when subscribing to events using $scope.$on. The process involves: An object is broadcasted using $rootScope.$broadcast, label ...

Enhance vuelidate by incorporating personalized validation functions

I am currently working on expanding the Vuelidate object within my Vue application. Here is the current setup in my Vue Component: import {required} from "vuelidate/lib/validators"; export default { validations: { ... } } In order to a ...

What is the correct way to generate an await expression by utilizing recast/esprima?

I have an issue with a JavaScript function export const cleanUp = async () => { await User.destroy({ where: {} }); }; I am attempting to add a line below await User.destroy({ where: {} }) using recast.parse(`await ${module}.destroy({ where: {} } ...

Encountered a Django MongoDB exception while running the syncdb command

My current setup includes django 1.5.5 along with django-mongodb-engine version 0.5.1. To install djangotoolbox, I used the command below: sudo pip install git+https://github.com/django-nonrel/djangotoolbox After installation, the djangotoolbox version ...

During the deployment of a ReactJS app, webpack encounters difficulty resolving folders

While developing my ReactJS app, everything ran smoothly on localhost. However, I encountered some serious issues when I tried to deploy the app to a hosting service. In my project, I have a ./reducers folder which houses all of my reducers. Here is the s ...

Troubleshooting Issue 415: Adding and modifying database records through jQuery AJAX in ASP.NET 6.0 MVC Application

Implementing the Add/Edit functionality for categories in my project led me to utilize a modal (pop-up) to transfer data to the backend without refreshing the page. To achieve this seamless interaction, I opted for ajax integration. However, encountering a ...

Storing data in a JSON format

Our team requires a service that can periodically generate up-to-date JSON data every 15 minutes for our AJAX services to consume. This JSON will be used for metric analysis and charts among other things. The reason behind the 15-minute interval is due to ...

What is the most effective way to retrieve emoji images in a chat using DiscordJS?

I am aiming to create a function that allows me to run a simple command like $yoink. This command would essentially convert the last sent emoji in the chat into an image that I can then download. I have a similar functionality already set up, however, it c ...

Implementing Vuetify tooltips in a datatable

Attempting to incorporate tooltips into a vuetify datatable, but encountering issues. Below is the required template for using a tooltip: <template v-slot:item.state="{ item }"> <div :class="lights(item)"></div> </template> Im ...

Using Scala with MongoDB

Recently, I have delved into the realms of MongoDB and Scala language, exploring ways to connect to MongoDB locally using Scala. To achieve this, I have included the following dependency: // libraryDependencies += "org.mongodb.scala" %% "mo ...

Troubles encountered when trying to display a Plotly OHLC plot using EJS and transferring data

I'm encountering an issue while trying to display a Plotly OHLC plot in my chart.ejs file with the variable result. Even after using EJS templating and <script> tags for logic, the plot fails to render. To address this, I created a separate file ...

When searching by ID in MongoDB, the query may come back empty

Recently delving into the world of NodeJS and MongoDB, I find myself facing a roadblock. Despite my best efforts, a very basic task seems to be eluding me. I am certain that something crucial is slipping past me. My current objective revolves around lo ...

What is the equivalent of `$exists: false` in Postgres when using MongoDB?

In MongoDB, the $exists operator is used to determine whether a key exists in a document or not. This operator works with the boolean values true and false. PostgreSQL can also store JSON data. What is the equivalent PostgreSQL query for the following Mon ...