What is the best way to extract specific information from a deeply nested document in MongoDB?

In my database, I have the following data structure.

[
  {
    _id: ObjectId("6386ef039775398be3620c76"),
    firstName: 'A',
    lastName: 'BA',
    age: 34,
    history: [
      { disease: 'fever', cured: true },
      { disease: 'malaria', cured: false }
    ]
  },
  {
    _id: ObjectId("6386ef239775398be3620c77"),
    firstName: 'AA',
    lastName: 'BA',
    age: 24,
    history: [
      { disease: 'cold', cured: true },
      { disease: 'thyroid', cured: false }
    ]
  }
]

I am trying to create a query that will retrieve data like this:

Query

 db.collection.find({$filter:{history:{$elemMatch:{cured:false}}}

Expected Result:

[
  {
    _id: ObjectId("6386ef039775398be3620c76"),
    firstName: 'A',
    lastName: 'BA',
    age: 34,
    history: [
      { disease: 'malaria', cured: false }
    ]
  },
  {
    _id: ObjectId("6386ef239775398be3620c77"),
    firstName: 'AA',
    lastName: 'BA',
    age: 24,
    history: [
      { disease: 'thyroid', cured: false }
    ]
  }
]

Here are the queries I have tried:

1.

db.collection.find({$filter:{history:{$elemMatch:{cured:false}}}
  db.collection.aggregate([
    {
      $project: {
        history: {
          $filter: { 
           input: "$history",
            as: "items",
            cond: { cured: false } 
          },
        },
      },
    },
  ]);
db.collection.find({history:{$elemMatch:{cured:true}}},{'history.cured':1})

However, none of these queries are producing the desired result.

Doubts/ Questions:

  1. Is it possible to directly obtain the expected result from a query?
  2. Where did my queries go wrong?
  3. Which resources should I refer to for more advanced concepts related to this query?

Any assistance would be greatly appreciated. Apologies if this question seems too elementary.

Answer №1

To optimize your query attempts, consider combining them into one streamlined process:

  1. Retrieve all documents containing an item with cured: false
  2. Utilize the $filter function within the history array to narrow down the results
db.collection.aggregate([
  {$match: {
      history: {$elemMatch: {cured: false}}
  }},
  {$set: {
      history: {
        $filter: {
          input: "$history",
          cond: {$eq: ["$$this.cured", false]}
        }
      }
  }}
])

Test this approach using the example in Mongoplayground

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

Performing logical AND and OR operations between two collections in MongoDB

Looking to process data from two different collections - specifically the apple and lime collections within the fruit db. The goal is to query categories O and W in the apple collection, then identify which items have been active in the last 3 days. Using ...

The React function was misusing the useEffect hook, causing it to be

I seem to be encountering a problem when trying to call useEffect within this function. As someone who is relatively new to React, I may have made some noticeable mistakes, but dealing with this issue is becoming quite time-consuming. The function in ques ...

Building intricate structures in Typescript: A comprehensive guide

My objective is to create a sophisticated object, with values that need to be calculated or extracted from another object. The specific object I am working on is defined as follows: interface A extends B { key1: string key2: { it's a complex object ...

Ensure the URL is accurate when making an AJAX request using JavaScript

My GET ajax call is structured like this: var changeUrl = "changePriority?newValue=" + targetValue + "&justification=" + justification if (dataInfo == "row") { changeUrl += "&id=" + id } changeUrl += "&executedConfigId=" + executedConfigId ...

What are some strategies for handling analytics tracking in Flux architecture?

Imagine I'm working on a cutting-edge single page application similar to Airbnb. One essential aspect of such an application is keeping track of when someone signs up for an account. There are numerous services available to assist with tracking, incl ...

Announcing libraries as constants

When working in the NodeJS environment, modules are imported using the require function: var foo = require ("foo"); In JavaScript (including NodeJS), we also have the const keyword for creating constants: const This creates a constant that may be globa ...

Personalized HTML ProgressBar featuring indicators

As I explore options for creating a progress bar/timeline with the ability to add markings (white lines shown in the image below) upon clicking a button, I've looked into HTML5 canvas and custom jQuery solutions. I'm curious if anyone has any spe ...

Is it possible to utilize the Time-to-Live feature of mongoDB to remove an item from an array?

I have been searching online and all I could find was information about deleting the entire document. However, what I actually want to do is delete a specific object in an array that is within a document. Here's an example: { _id: "ID OF A SPECIFIC ...

Angular factory functions that include .success and .error methods

I am new to using Angular and I'm curious about the recommended best practices for placing the .success and .error functions. Should they be within the controller or within the factory? Here are two examples: Option 1: (function(){ 'use str ...

Highcharts - resolving cross-browser e.Offset discrepancies in mouse event detection on charts

I need to determine if the mouseup event is inside the chart and display the coordinates of the point. The code works in Chrome but not in Firefox due to the lack of the event.offset property. jQuery(chart.container).mouseup(function (event) { eoff ...

maximum number of records allowed in a nested document in MongoDB

My goal is to develop a messaging system that allows for group conversations among multiple users. Each user involved in the conversation should be able to view the entire chat, and any participant can introduce new users into the discussion if it's n ...

Unused custom function

Attempting to implement an exclude button for the multi_select filter_type, utilizing multi_select_custom_func. Also experimenting with custom_funcp. The issue at hand is the custom function never gets invoked. I have verified that it falls within yadcf&ap ...

Unraveling an AJAX response in JSON format using jQuery

I am a beginner in the world of Jquery and Ajax. I've crafted the code below to automatically populate a form with data after selecting an option from a combo box within a form, using guidance from this helpful post Autopopulate form based on selected ...

Discovering the date's year and tallying the number of records per year

I have a CSV file that has the following format: Name, Age, Date of Birth (M/D/Y as a string). I am looking to extract the year from the 'Date of Birth' field and then calculate the number of people born in each year. The desired outcome should b ...

Selecting either "THREE.NearestFilter" or "THREE.LinearFilter" will result in the black plane

During my experimentation with the THREE.js library, I encountered a notification stating: THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter. To address this issue, I made the ...

Asynchronous Return in NodeJS Class Methods

Currently, I am in the process of developing a JavaScript class that includes a login method. Here is an overview of my code: const EventEmitter = require('events'); const util = require('util'); const Settings = require('./config ...

Tips for handling a promise that has not been fulfilled

Is there a way to return a promise and trigger its failure block right away? Check out this unconventional method: if (fail) { var q = $q.deferred(); $timeout(function() { q.reject("") }, 1); return q.promise; } else { return ...

Output a variable that is generated from invoking an asynchronous function

I'm currently in the process of developing an application that is going to leverage the capabilities of a SOAP server through the use of the https://github.com/vpulim/node-soap module. One of the main challenges I am facing is how to efficiently crea ...

Node.js mongoose shows poorer performance in comparison to mongo shell or robo3t when it comes to speed

I have a query that produces approximately 300 results using aggregate functions. Interestingly, when I run the query in robo3t or in the mongo shell, it executes very quickly. However, when I try to execute it using mongoose in NodeJs, it is extremely sl ...

When the value is inputted into the textbox and the enter key is pressed, a fresh chip displaying the entered value will materialize

Whenever I click on a textbox, a menu opens that requires me to enter a value in the textbox. After entering the value and hitting enter, a new chip with the entered value should appear. I tried creating an Onchange event to pass the values to the chip com ...