Combine array in MongoDB containing nested documents

I need assistance with querying my MongoDB database:

Specifically, I want to retrieve data that is nested within an array and filter it based on a specific key within the nested structure.

The example document looks like this:

[
  {
    "name": "PharmaMaria",
    "country": "Spain",
    "currency": "EUR",
    "medicines": [
      {
        "name": "Medicine 1",
        "type": "Suncream",
        "price": 32,
        
      },
      {
        "name": "Medicine 2",
        "type": "Suncream",
        "price": 5
      },
      {
        "name": "Medicine 3",
        "type": "Pills",
        "price": 7
      }
    ]
  }
]

My goal is to extract data similar to the following by filtering using medicines.type

values = [
  {
    "name": "Medicine 1",
    "price": 32
  },
  {
    "name": "Medicine 2",
    "price": 5
  }
]

You can explore the query in action at this Mongoplayground link: https://mongoplayground.net/p/_riatO8PKVp

Thank you for your help!

Answer №1

You need to incorporate a $project or $addFields stage in your aggregation pipeline and utilize the $filter operator to apply conditions on each element.

db.collection.aggregate([
  {
    "$match": {
      "country": "Spain",
      "medicines.type": "Suncream"
    },
    
  },
  {
    "$addFields": {  
      "medicines": {  
        "$filter": {  
          "input": "$medicines",
          "as": "elem",
          "cond": {  
            "$eq": [
              "$$elem.type",
              "Suncream"
            ],
            
          }
        }
      }
    }
  },
  
])

If you only want specific keys from an array, you can make use of $map.

db.collection.aggregate([
  {
    "$match": {
      "country": "Spain",
      "medicines.type": "Suncream"
    },
    
  },
  {
    "$addFields": {
      "medicines": {
        "$map": {
          "input": {
            "$filter": {
              "input": "$medicines",
              "as": "elem",
              "cond": {
                "$eq": [
                  "$$elem.type",
                  "Suncream"
                ],
                
              }
            }
          },
          "as": "med",
          "in": {
            "name": "$$med.name",
            "price": "$$med.price",
            
          }
        },
        
      }
    }
  },
  
])

Explore Mongo Execution Sample Here

Check Out Mongo Playground for Execution Example

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

Is it possible to execute a custom npm script before launching the server on AWS ElasticBeanstalk deployment?

I've been struggling to successfully deploy my Nuxt universal app on AWS Elastic Beanstalk. I attempted using a custom npm script in my package.json: "scripts": { "dev": "nuxt", "build": "nuxt build", "start": "nuxt start", "generate": "nuxt gene ...

Having trouble with Google Maps Places API autocomplete feature; it's not functioning properly

My goal is to integrate the Google Maps Places API with a search box. To test jQuery autocomplete, I managed to make it work using this simple example: function bindAutocomplete() { var locationSearch = $("input#Location"); locationSearch.autocom ...

Should scripts be replayed and styles be refreshed after every route change in single page applications (SPA's)? (Vue / React / Angular)

In the process of creating a scripts and styles manager for a WordPress-based single page application, I initially believed that simply loading missing scripts on each route change would suffice. However, I now understand that certain scripts need to be ex ...

Tips for effectively managing the timeout of server-side AJAX calls1. Maxim

I'm currently developing server code in ASP.NET with the MVC framework. The client-side code is written in javascript. When sending an AJAX request from the browser to the server, whether using JQuery or not, timeouts can be set. Additionally, the br ...

How to extract hrefs within <li> tags from a <ul> element with Cheerio

I'm facing some difficulties with this question, so I need your help. What I want to achieve is to extract the hrefs from the HTML provided below. <ul id="nav-products"> <li><a class="" href="/shop/hats/">yellow good looking ha ...

Retrieve the div element by calling a scriptlet with JavaScript

I am facing an issue with a web page that includes a scriptlet like this: <div id="flash_chart"> <%=content_data['report_text']%> </div> The variable content_data['report_text'] contains a lengthy string ...

Adjusting the color of specific sections within a text box

Can I change the color of a specific section of a text input box? I'm working on a comment widget that needs everything between the @ and : symbols to be in a different color: <input type="text" placeholder="Want To Say Something?" value="@user55 ...

Guide on utilizing the <source> tag within v-img component in Vuetify.js?

When it comes to using webp images instead of jpg or png, some browsers may not support the webp format. In such cases, we can use the html tag < source > as demonstrated below, ensuring that at least a jpg image is displayed: <picture> < ...

"Resolving problems with file uploads in Angular JS, Express JS, and Node

Need some assistance I'm still new to this and when it comes to file uploads, I found help from this resource - Below is my implementation. I've omitted certain parts to ensure readability of the post size. The main issue lies with the file upl ...

Ways to retrieve all local variables in an Express view

I'm exploring options to access all the app.locals within views. Here's what I have in my app.js: app.locals.title = "Title" app.locals.page = "Page 1" These work fine, and I can easily use them in views like this: <%= title %&g ...

Sort the results by total count in Mongoose Express Node.js after grouping by id

I have a unique collection of items: { "_id": { "$oid": "5f54b3333367b91bd09f4485" }, "items": [ { "_id": 20, "name": "Turkish Coffee", "price": ...

Visual Studio Code unable to locate source maps for typescript debugging

Looking for some help debugging a basic Hello World TypeScript file. Whenever I try to set a breakpoint, it seems like VS Code is having trouble locating the source map, even though it's saved in the same directory. I'm using Chrome as my browser ...

Is Python a suitable programming language for developing applications on a Raspberry Pi device?

I'm diving into the coding world for the first time and I have a project in mind - controlling my RC car with my smartphone using a Raspberry Pi 3. Research suggests that I should use Node.JS and JavaScript to create the app, but I'm wondering if ...

Combining load and change events in jQuery at the same time

Often times, I find myself needing to attach a behavior to an element both after it has loaded and after a specific event has been triggered (such as "change"). I believe the most efficient approach would be to combine these actions in one line: $('# ...

Using CSP with strict-dynamic for script-src along with hash is preventing the loading of resources from the

My front end is built with React (create-react-app, not ejected) and my back end uses Node/Express. I have implemented the following CSP configuration: app.use( helmet.contentSecurityPolicy({ directives: { 'script-src': [ "&a ...

Which is the better option for opening a link in a button: using onclick or href?

What is the most effective way to open a link using a button? <button type="button" onclick="location='permalink.php'">Permalink</button> <button type="button" href="index.php">Permalink</button> ...

Unable to establish session property within an Express Route Middleware

Currently, I am working on developing an API using NodeJS and Express. When attempting to call the route /api/news/1, I encounter a TypeError in the console: var express = require('express'); var app = express.createServer(); app.configure(fun ...

JavaScript - Combining nested arrays of JSON data into a single object

I'm looking to convert a nested JSON structure into a single object with dynamic keys. I attempted the code below, which only works for one level. I need help writing a recursive function to handle n levels of nesting. Any advice would be appreciated. ...

Animate images using mouse vertical movement

Creating websites is just a hobby for me, not something professional. Recently, I came across a beautifully designed website that had some unique features I hadn't seen before, like placing three images in one div (which I researched and learned how t ...

Ways to showcase JSON data with jQuery

My code displays movie data from a JSON variable and populates it on a dropdown list based on the selected city. I aim to include show timings along with other details from the JSON content. The code snippet is as follows: $(document).ready(function() ...