Querying and Retrieving a List of Nested Documents in MongoDB

I have multiple solutions, each of which may contain various projects. To represent this relationship, I opted for embedding the projects within the solution document. For example:

[{
    _id: "1",
    solutionTitle:  "Some Sample Solution",        
    projects: [
      {
         _id: "12",
         type: "Java",
         title: "Sample Project"
      },
      {
         _id: "13",
         type: "Misc",
         title: "Demo Project"
      }
    ]
 },
 {
    _id: "2",
    solutionTitle:  "Another Solution",  
    projects: [
      {
         _id: "21",
         type: "Java",
         title: "Another Java Project"
      }
    ]
 }]

Now, I aim to retrieve all projects of a specific type, such as Java. I attempted the following query using aggregation:

db.Solutions.aggregate ( 
    { "$unwind": "$projects" }, 
    { "$match": {"projects.type": "Java" } }, 
    { "$project": {"projects" : 1, "_id": 0, "solutionTitle": 0 } } 
)

While this query works correctly, the result is not in the format I anticipated. The output looks like:

{
    projects: {
        _id: "12",
        type: "Java",
        title: "Sample Project"
    },
    projects: {
        _id: "21",
        type: "Java",
        title: "Another Java Project"
    }
}

Is there a way to structure the result as a list of projects, for instance:

[
    { _id: "12", type: "Java", title: "Sample Project" }
    ...
]

I have reviewed this SO thread and this one but they do not exactly address my requirement. Any assistance would be highly appreciated.

Answer №1

To store them in an array, you must include them in an array:

db.Solutions.aggregate([
    { "$unwind": "$projects" }, 
    { "$match": {"projects.type": "Java" } }, 
    { "$group": {"_id": null, "projects": { "$push": "$projects" } } }
])

Based on your feedback below, it appears that what you truly desire is to retrieve the project subdocuments as if they were the main documents being searched for. If so, you should explicitly $project your project values:

db.Solutions.aggregate ([
    { "$unwind": "$projects" }, 
    { "$match": {"projects.type": "Java" } }, 
    { "$project": {"_id": "$projects._id", "type": "$projects.type", "title": "$projects.title" } }
])

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

Tips on hiding specific table rows in two separate tables based on the chosen option from a dropdown menu

How do I hide table rows based on dropdown selection? The first table has a dropdown with two options: Current State and Future State. If I select Current State, I want to show or hide specific rows in the 2nd and 3rd tables. I am using IDs for these row ...

Discovering the final pattern using regular expressions

var inputString = 'a.b.c.d.e.f'; var pattern = inputString.match(/([^\.]+)\.[^\.]+$/)[1]; console.log(pattern); I have successfully implemented the code using regular expressions, but I am open to exploring more efficient solution ...

Leveraging ES6 with jQuery in Symfony 4

Currently working on a simple app using Symfony 4 and trying to add custom triggers in JavaScript. Having trouble getting my additional code to work as expected, even though it's compiled by Webpack via encore. It seems like my event is not triggering ...

What is the best way to use AJAX to send a downloadable file in WordPress?

Currently working on developing a WordPress plugin and could use some assistance ...

Update the div content to completely replace it with fresh data using Ajax

I'm currently working on implementing a currency switcher feature for my website, allowing users to toggle between two different currencies. The site is a reservation platform with a booking form displayed on the left side and the booking details occu ...

Looking for a way to extract Regular Expressions from an IgGrid cell in Infragistics?

Is it possible to apply a regular expression to a igTextEditor within an igGrid Updating? I attempted to utilize the validate option, but it was unsuccessful. $("#schedulerTable").igGrid({ columns: $scope.schedulerColumns, widt ...

How can I add a blank selection at the bottom of my ng-options dropdown?

At the moment, my setup looks something like this (in a simplified form): <select ng-model=model.policyHolder ng-options="person.index as person.name for person in model.insurance.persons"> <option value>Someone else </select> This co ...

Uh-oh, the Next.js fetch didn't go as planned. The error message

Currently, I am using Next.js 14 for my project. Suddenly, there has been an issue where some images are not loading on my local setup. However, the images load fine on the preview and production branches on Vercel. Upon checking my console, I noticed th ...

Error: React unable to locate module './WebpackMissingModule'

Recently I started diving into React, and I'm encountering some difficulties trying to export components. Here is my current index.js file setup: import React from 'react'; import ReactDOM from 'react-dom'; import SearchBar from ...

Enumeration field with Conditional logic

I am currently developing a Content Management System (CMS) using strapi for a client, and I want to provide them with the ability to control the questions included in a questionnaire. Each question will be categorized under different sections in the quest ...

Veracode Scan finds vulnerability in jQuery html method with Improper Neutralization of Script-Related HTML Tags in a Web Page error

Veracode has flagged the issue Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS) within the following line of code. $('#SummaryDiv').html(data); $.ajax({ url: 'Target_URL', type: &a ...

Editing the object retrieved from JSON is not possible once it has been fetched

Project. Input text in the field and it appears on the shirt. When you click "see back," there is an issue where new text overlaps old text. Clicking on "see front" allows you to enter new text, with the previous text saved underneath. Question: How can ...

When running the `vue-cli-service test:unit` command, an error involving an "Unexpected token" message related to the usage of the spread operator

Within my code, I am utilizing the destructuring operator. However, during the module build phase, I encountered an "Unexpected token" error. Any suggestions on how to resolve this issue without completely rewriting my code to avoid using the destructuring ...

What is the best way to determine the amount of distinct elements in an array of objects based on a specific object property?

I am working with an array called orders. orders = [ {table_id: 3, food_id: 5}, {table_id: 4, food_id: 2}, {table_id: 1, food_id: 6}, {table_id: 3, food_id: 4}, {table_id: 4, food_id: 6}, ]; I am looking to create a function that can calculate ...

Unable to get ajax Post to function properly

Looking to save an object on a restful server, I attempted using an HTML form which worked fine. However, when trying it with JavaScript, I encountered some issues. Here's the code snippet: var app2={"user_id" : seleVal, "name":nome2, "img":img2, "ty ...

I'm looking to configure @types for a third-party React JavaScript module in order to use it with TypeScript and bundle it with webpack. How can I accomplish this?

Imagine you have a third-party npm package called @foo that is all Javascript and has a module named bar. Within your TypeScript .tsx file, you want to use the React component @foo/bar/X. However, when you attempt to import X from '@foo/bar/X', y ...

Guide on altering the background color of a table row depending on the data in its cells with the help of AngularJS

I am looking to dynamically change the background color of a row based on specific cell data. If the first four characters in a table cell match a certain value, I want the entire row to change its color to red. Currently, my code changes the row color ba ...

What is the best way to make an exit pop up disappear when clicking on any area?

I'm new to programming in JavaScript and jQuery and I wanted to implement an exit pop-up feature. While I came across a helpful tutorial online, I encountered an issue where users could only exit by clicking on the "X" button. I want them to be able t ...

Error Encountered: Module Not Located

I am encountering an error in my Project where it keeps showing 'Cannot find module' even after numerous attempts to install and uninstall packages simultaneously. The problem persists, and I can't seem to resolve it. { "name&quo ...

Add the slide number and total count in between the navigation arrows of the owl carousel

In my Angular application, I am utilizing an ngx owl carousel with specific configurations set up as follows: const carouselOptions = { items: 1, dots: false, nav: true, navText: ['<div class='nav-btn prev-slide'></div>' ...