Performing MongoDB aggregation on an array of nested objects containing date properties

Here is a sample of the data I have:

{
  "_id": ObjectId("52ed12c144aecc4bf004d0b6"),
  "active": true,
  "name": "woslo",
 "specialDays": [
  {
  "_id": ObjectId("5f0576196198a715b0a72c14")
  "status": true
  "date": 2020-07-08T04:00:00.000+00:00
  },
  {
  "_id": ObjectId("5f05a3726198a715b0a72c94")
  "status": false
  "date": 2020-07-09T04:00:00.000+00:00
  }
 ]
}

I am trying to retrieve records using this query:

   db.serviceProviders.aggregate([
    {
      $match: {
            specialDays: {
              $elemMatch: {
                $or: [
                  {
                    $and: [
                      {
                        date:  model.date // 2020-07-09T06:00:00.000Z
                      },
                      {
                        status: true
                      }
                    ]
                  },
                  {
                    date: {
                      $ne:  model.date //2020-07-09T06:00:00.000Z
                    }
                  }
                ]
              }
            }
          }
        }
  ]);

The scenario is as follows: if the date is present in the specialDays array and the status should be true, or the date should not be in the specialDays object's array, then fetch this record. However, it keeps returning the same record even when the status is false or the date is in the array. Can you please assist me in finding a solution? I have tried multiple MongoDB Compass aggregation queries with ISODate('2020-07-08') but without success. Thank you and happy coding.

Answer №1

There seems to be an issue with the $ne condition in your code. When status is false, the $ne condition evaluates to true due to logical OR operation, leading to the current output.

Have you tried this solution?

db.collection.aggregate([
  {
    $match: {
      specialDays: {
        $elemMatch: {
          $or: [
            {
              $and: [
                {
                  date: new Date("2020-07-09T04:00:00.000+00:00")
                },
                {
                  status: true
                }
              ]
            },
            {
              date: {//Changes here
                $gte: new Date("2020-07-09T06:00:00.000+00:00"),
                $lte: new Date("2020-07-09T23:59:59.000+00:00")
              }
            }
          ]
        }
      }
    }
  }
])

Alternatively,

try this approach.

Another reason why your $ne condition is evaluating to true could be because it matches the first array element in the specialDays array.

db.collection.aggregate([
  {
    $match: {
      specialDays: {
        $elemMatch: {
          $or: [
            {
              $and: [
                {
                  date: new Date("2020-07-09T04:00:00.000+00:00")
                },
                {
                  status: true
                }
              ]
            },
            {
              $and: [
                {
                  date: {
                    $ne: new Date("2020-07-09T04:00:00.000+00:00")
                  }
                },
                {
                  status: false
                }
              ]
            }
          ]
        }
      }
    }
  }
])

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

Troubleshooting state issues with Vuex and Firebase

Within my vuex store, I have a setup where users are authenticated using Firebase. After logging in, the firebase.auth().onAuthStateChanged function is triggered, setting the user variable to state.user and saving it in the Firebase database. However, when ...

How to give focus to a div in IE 8 after pressing the tab key, no jQuery required

We are facing a challenge with our datagrid where we have implemented navigation using the tab key. In IE 7 & 8, pressing the tab key shifts the focus away from the grid to the next element on the page. While in other browsers, we were able to prevent thi ...

Exploring methods to retrieve the previous item in a Dropdown list using jQuery or JavaScript

Is there a way to retrieve the previously selected value of a dropdown control using jquery or javascript? I attempted using the prev() selector in jQuery but encountered issues. $(ddlStatus).find("option").prev(":selected").attr("text"); For example, if ...

Executing Multiple Requests Concurrently in Angular 5 using forkJoin Technique

Important Note The issue lies in the backend, not Angular. The requests are correct. In my Angular5 app, I am trying to upload multiple files at once using rxjs forkJoin. I store the requests in an array as shown in the code below. However, after adding ...

Creating a custom string subtype in TypeScript

I am currently working on developing a game called Risk using TypeScript and React hooks. This game is played on a map, so my first step was to design a MapEditor. The state of the Map Editor is as follows: export interface IMapEditorState { mousePos: ...

Accessing Child HTML Elements with VueJS2

When working with Vue, I usually use the ref keyword to access components. However, I am struggling to understand how to access HTML tags from within a component. I attempted: <input type="text" ref="searchAddress" id="searchAddress" name="searchAddre ...

Exploiting the Benefits of Multiple BaseURLs with Require.js

My project has a structure that resembles the following: /path/to/project /apps /app1 /js /modules /bar.js /etc.. /app1.js /app1.build.js ...

Instructions on how to assign a function to a dynamically created button in Angular 2

I recently created a table that can generate a new row when the addRow() function is called. However, I am facing an issue where the button in the generated row is not able to call the myFunc() function. How can I resolve this problem? addRow(){ let t ...

Perform a bash command using PHP when an HTML button is clicked

Today, my brain seems to be on vacation. Currently, I have set up a Raspberry Pi with vlc running and connected to a mounted screen on the wall. There is a web page with simple controls to manage the pi, switch between different vlc streams, or stop stream ...

AngularJs input field with a dynamic ng-model for real-time data binding

Currently facing an issue with my static template on the render page. <form name="AddArticle" ng-submit="addArticle()" class="form add-article"> <input type="text" value="first" init-from-form ng-model="article.text[0]" /> <input typ ...

Unable to access the internal function of an Angular controller

My goal is to invoke the inner function of an Angular controller. index.html <script type="text/javascript> $(document).ready(function() { $('#example').multiselect({ onChange: function(option, checked, ...

Troubleshooting MongoDB database errors

My Ubuntu 14.04.3 LTS server has a MongoDB 3.0.2 database with a data directory size of 3.5 TB. After experiencing hardware issues with the RAM, the database is now facing performance issues such as server crashes and endless request processing. Unfortunat ...

Enhance Your Website with Bootstrap 3.0 Affix

Looking to attach a right hand column to the top of the window as you scroll using Bootstrap 3.0 and 'affix' feature. Here is the HTML for the element: <div class="col-lg-4 right-hand-bar" data-spy="affix" data-offset-top="477"> This is ...

Using React and Typescript, implement an Ant Design Table that includes a Dropdown column. This column should pass

Next Row: { title: "Adventure", render: (item: ToDoItem) => { //<- this item return ( <Dropdown overlay={menu}> <Button> Explore <DownOutlined /> </Button> </Dropdown&g ...

Compiling a Chrome extension popup with background reference using Closure Compiler

Developing a Chrome extension involves working with the scripts background.js and popup.js. Within background.js: function foo(){ // Performs some action } In popup.js: var backgroundPage = chrome.extension.getBackgroundPage(); backgroundPage.foo(); ...

Using AOS in WordPress causes the specified elements to appear as blank rather than fading in

Struggling to integrate Michalsnik's Animate On Scroll plugin into my Wordpress site. Followed the instructions to add the "data-aos" attribute to a div, but the element ends up being blank instead of fading in. <div class="textbox center branch-b ...

Passing state from React.JS to a link results in an undefined props.location.state

I am facing an issue with passing state to the Link component. When trying to access the state using props.location.satate, it comes up as undefined. Even after attempting to send the state through the to attribute using both pathname and state, it remains ...

The execution of JS code is being hindered by PHP codeigniter

Utilizing some pre-owned code in my current project The code snippet below is responsible for adding a product to the wishlist within the view <p class="p"><a<?php echo "onclick='addtowishlist($product->id)'"; ?>>Add To W ...

The sluggishness of the comment system is attributed to the intricate layers

A new photo viewing and commenting system has been developed, allowing users to interact with albums. When a user clicks on an album, they are directed to a page where the first photo, along with comments and replies, is displayed in the center. All other ...

What is the best method to pass the URL from the browser to the backend in a Node.js environment?

Currently, I am utilizing the MEAN Stack for my project and I'm passing the user ID as a parameter in the URL. <div> <% users.forEach( function( user ){ %> <li><a href=""><%= user.username %></a></li> ...