Is there a way to search across multiple fields using $elemMatch in Mongoose?

I have a data model that keeps track of different activities, including any problems or errors:

activities?: {
  message?: string;
  data?: any;
  issue?: {
    errors?: AVError[];
    dismissed?: {
      timestamp: string;
      message?: string;
    };
  }
}[];

I am looking to retrieve records that do not have any unresolved issues in the activities section.

Every attempt I've made so far has not been successful. The latest query I tried is:

collection.find({
  activities: {
    $not: {
      $elemMatch: {
        issue: { $exists: true },
        'issue.dismissed': { $exists: false },
      },
    },
  },
});

This query works for cases where there are no reported issues or when all issues are resolved, but it fails to identify records with unresolved issues.

Another approach I attempted was:

collection.find({
    $or: [
      { 'activities.issue': { $exists: false } },
      {
        'activities.issue': { $exists: true },
        'activities.issue.dismissed': { $exists: true },
      },
    ],
});

Unfortunately, this method also missed some records with dismissed issues.

While I can manually filter the results after retrieving all the data, I believe there should be a way to handle this within a single Mongoose query.

Answer №1

It's a bit unclear what you're searching for, but based on my understanding:

I need to execute a query that identifies all entries without any activities linked to unresolved issues (i.e. dismissed does not exist).

In other words:

I'm looking for items where all values within activities are associated with an issue.

Therefore, the concept of "no activities with unresolved issues" can be simplified as "all listed activities have resolved issues."

I believe the query you provided is close to what you need. I tested it and it seems to align with my interpretation:

db.collection.find({
  "activities": {
    $not: {
      $elemMatch: {
        "issue.dismissed": {
          $exists: false
        }
      }
    }
  }
})

Check out an example here.

In the sample scenario I created, only documents containing activities paired with issues are returned. This includes cases where there are no activities at all, which was achieved by incorporating

{ 'activities.issue': { $exists: false } },
into the $or clause, assuming that's what you intended. However, if you wish to exclude such scenarios, consider using this alternative query instead.

The main distinction from your initial query is in including issue: { $exists: true },, which results in entries featuring activities but without corresponding issues also being included in the results.

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 created a new game where I can select two images to display, but for some reason, it is only showing one

My rock paper scissors game functions well, except for one issue. I programmed it to display both the player's choice and the bot's choice along with an outcome message (win, tie, or lose). However, I encountered a problem where only the player&a ...

Analyzing and swapping objects within two arrays

Looking for a better way to append an array of objects customData to another array testData? If there are duplicate objects with the same name, replace them in the resulting array while maintaining their order. Here's my current approach in ES6 - any ...

Easily manage and store substantial amounts of data (exceeding 5MB) across various pages during navigation

When navigating through various steps or pages of my website, I am in need of a reliable way to store different information. Currently, I am using sessionStorage as shown in the example below: sessionStorage.setItem("src", "" + $('#newImage').at ...

Watching the $scope variable using $watch will result in triggering even when ng-if directive is used, displaying

Encountering an unusual behavior in AngularJS that may appear to be a bug, but there could be a logical explanation. A certain value is being passed to a directive as an attribute. Within this directive, the parameter is being watched using $scope.$watch. ...

Unable to establish connection to MongoHQ using Node.js connection URL

I have successfully set up and run a Node.js app using my local development MongoDB with the following settings and code: var MongoDB = require('mongodb').Db; var Server = require('mongodb').Server; var dbPort = 27017; v ...

Is it possible to modify the host header within an Angular app?

I'm experiencing a vulnerability issue and to resolve it, I need to utilize SERVER_NAME instead of the Host header. Is it possible to accomplish this using Angular? ...

The error message "Conflict Between Editor Elements Detected (Code: CKEDITOR Error code

Incorporated within my web application is the CKEditor jquery adapter which functions smoothly, however, a console error appears: Upon consulting the CKEDITOR dev error documentation, I found an explanation for the error but unfortunately no solution was ...

Saving website configuration settings as a Mongoose schema

I am currently storing my website configuration as a JSON file and I am considering moving it to MongoDB. I am thinking of using Mongoose to handle read-write operations and validate the data with schemas. The configuration consists of an object with a li ...

React-big-calendar: Customize day view to end at 1 am for multiple days

I'm currently in the process of developing a booking system and utilizing react-big-calendar for this project. Situation: A business operates from 9am to 2am the next day, allowing clients to book appointments between 11pm and 1am. Objective: To sho ...

The Challenge of Cross-Origin Resource Sharing in WebAPI

I'm working on a basic webapi project with default controllers. I need to access the same values from an HTML page using an ajax request. Key Points: Retrieve the token using the token method Pass the token to get the values Client-Side: Below is ...

Splitting AngularJS Controllers Into Individual Files

I'm currently utilizing Ui-Router in my AngularJS project and I'm seeking a way to organize my angular controllers into separate files for better organization. For instance: var app = angular.module('myApp', ["xeditable", 'ngRout ...

Utilizing ExpressJS to save uploaded files using the FileReader object from the front-end

Despite researching multiple posts on this topic, I am still unable to successfully upload a file after numerous adjustments. My React form includes a PDF file upload component which looks like this: <Input onChange={(e) => this.handleFileUpload(e) ...

Utilizing Bootstrap Modal functionality in a Django web application to enhance user experience

I am currently facing a minor issue in my Django application. I am attempting to utilize a modal from Bootstrap 4 along with AJAX to create a new object. Below you can view the code I used. However, when the user clicks the button, instead of seeing the mo ...

Looking to confirm the accuracy of file inputs on Node.js

I am currently developing my application using the Node + Express + MongoDB stack. Within my application, there are several forms for uploading files. While the uploading process works smoothly, I am facing an issue with the lack of validation for these fi ...

Building nested objects within an isolated scope can be achieved by following these steps

I am trying to implement a nested structure on my nested scope within a directive, as shown below: angular.module('myAddress').directive('myAddress', [function () { return { restrict: 'AE', controller: &ap ...

Can you explain the distinction between using angular.copy() and simply using an assignment (=) to assign values

When a button is clicked, I want to assign certain values using the event parameter. Here is the code: $scope.update = function(context) { $scope.master = context; }; The $scope.master has been assigned the values of user. Recently, I came across th ...

What are some ways I can safeguard my CSS from injected elements?

I have created an HTML widget that is inserted into various websites without the use of iframes. However, I am encountering issues where the CSS of some sites is affecting the appearance of my elements, such as text alignment, underlining, and spacing. Is ...

Discovering the specific URL of a PHP file while transmitting an Ajax post request in a Wordpress environment

I'm currently working on a WordPress plugin and running into some issues with the ajax functionality. The main function of my plugin is to display a form, validate user input, and then save that data in a database. Here is the snippet of code for my ...

How can you determine the size of an array in Mongodb?

I am currently dealing with two collections, namely posts and company. My goal is to display a list of posts along with some brief details about the company such as rating and totalReviews. This is the approach I have taken so far: db.getCollection(' ...

Utilizing Jquery to extract a specific string from a URL and fetch a remote element

Recently delving into Jquery, I'm in search of a code snippet that can capture the current page URL and load a remote element if it contains a specific string. For instance: Consider these sample page URLs: "http://......./Country/AU/result-search- ...