Retrieving deeply nested objects within an array of objects in MongoDB

Here is the structure of my database:

[
     {
      "title": "man",
      "articlesType": [
             {
                 "title": "shoes",
                 "articles": [
                     {
                         "title": "shoes1",
                         "id": "randomId"
                     },
                     {
                         "title": "shoes2",
                         "id": "alsoRandomId"
                     }
                 ]
             }
         ]
    },

    {
    "title": "woman",
    "articlesType": [
         {
             "title": "pants",
              "articles": [
                    {
                        "title": "pants1",
                        "id": "anotherRandomId"
                    },
                    {
                        "title": "pants1",
                        "id": "justId"
                    }
                ]
            }
        ]
    }
]

I am looking for a way to access a nested object by its ID. Can this be achieved?

{
   "title": "shoes2",
   "id": "alsoRandomId"
}

I have come across a solution, but unfortunately, it does not work for my case.

Answer №1

If you want to deconstruct an array twice in an aggregation pipeline, you can use the $unwind operator and then filter by a specific id. This is useful when you need to match by the id.

The final step involves using the $project operator to format the output as desired.

db.collection.aggregate([
  {
    "$unwind": "$articlesType"
  },
  {
    "$unwind": "$articlesType.articles"
  },
  {
    "$match": {
      "articlesType.articles.id": "alsoRandomId"
    }
  },
  {
    "$project": {
      "title": "$articlesType.articles.title",
      "id": "$articlesType.articles.id"
    }
  }
])

Check out an example here

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

Developing a dynamic row that automatically scrolls horizontally

What is the best method for creating a div box containing content that automatically slides to the next one, as shown by the arrows in the picture? I know I may need jquery for this, but I'm curious if there's an alternative approach. oi62.tinyp ...

Unable to stop the default action in IE for certain code

I am facing an issue on my website where the JavaScript I have implemented to prevent page reload is not working in Internet Explorer. The code functions properly in all other browsers, except IE. Here is the JavaScript code snippet that should prevent pa ...

Extract information from a JSON string and present it on the screen

I am a complete novice when it comes to D3 (with very little experience in JS). Here are the lines of code I am working with: <script type='text/javascript'> data ='{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.62,"qsec":16. ...

Parent window encountering issue while calling child window function

Recently, I have been encountering issues with using an iframe inside a thickbox and calling the function within the iframe. The code snippet I'm currently using is window.frames[0].test();, which seems to be working inconsistently across different br ...

Can the color of an ion-radio be adjusted when it is not selected?

I am experiencing an issue where I need to change the default color (grey) to a specific color of my choice, such as the primary color. I have attempted the following methods: <ion-col sizeXs="12" sizeMd="6" class="radio-box"> <ion-item line ...

I am currently having issues with the mustache syntax in vuejs, as it is not functioning properly

Having an issue with Vue.js where the mustache syntax isn't working properly. <!DOCTYPE html> <html> <head> <title>index</title> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cg ...

Guide to sending a similar request as a curl command through a JavaScript file

After reviewing this Stack Overflow post titled "JavaScript post request like a form submit", I came across a similar situation. Currently, I have a curl command that performs as expected: curl -v -X POST -H "application/json" -H "Content-type: applicatio ...

Verify if the contract address corresponds to a token and retrieve the token details, such as its symbol

Can I use web3 to retrieve token information such as symbol and total supply similar to the etherscan API pro endpoint tokeninformation by providing the contract address? I'm interested in determining whether the addresses I collect are tokens or reg ...

What is the best way to create a JavaScript animation for altering the width of a div element?

Need help with creating a dynamic poll chart based on YES and NO votes? Check out this project where you can visually see the results by clicking HERE. Looking to add some animation effects to your poll? You can achieve a smooth transition using CSS with ...

Replacing a string using Regular Expression based on certain conditions

When working with a node.js server, I encountered the need to modify URL addresses using JavaScript in a specific way: For instance: hostX/blah/dir1/name/id.js?a=b --> name.hostY/dir2.js?guid=id&a=b Another example: hostZ/dir1/name/id.js --> ...

Is it possible to exclude specific URLs from CSRF protection in sails.js?

I am currently integrating Stripe with my sails.js server and need to disable CSRF for specific URLs in order to utilize Stripe's webhooks effectively. Is there a way to exempt certain URLs from CSRF POST requirements within sails.js? I have searched ...

Discovering vacation days in the Persian calendar (Shamsi)

How can I access Persian calendar holidays in React without using paid APIs? Is there a free way to get information about Persian (shamsi) holidays, including descriptions? { 1402:[ { date: "1402/1/2", description: "عیدن ...

JavaScript pop-up purchase tooltips from MenuCool

I am relatively new to the world of web design and programming. I am putting in a lot of effort to learn as much as possible, but I am encountering difficulties with the tooltip JavaScript that I incorporated into my website Click here to visit my website ...

Navigate to a new page on button click using Row with Tanstack / React-Table and Typescript (2339)

Encountering a linting error when attempting to navigate to a new route by clicking on a table row. The functionality is working but how can I resolve this issue? It's showing an error message stating "The property "id" for type TData does not exist." ...

Introducing the innovative Icon Collapsable JQuery - a versatile tool that

I'm looking to set custom icons for the JQuery Collapsable view without having to make changes to the default JQuery CSS and .JS files. You can take a look at my starting point on jsFiddle here: http://jsfiddle.net/jakechasan/M7LLU/ Although I' ...

Joi validation that focuses on required array elements while disregarding nested keys

Why is my Joi array required validation not detecting an empty array? I have an array called userData that contains objects with keys dateMilli and value. Despite adding required validations everywhere, passing an empty array [] for userData does not resul ...

Stopping an AngularJS timeout from running

I have a multi-platform app created using AngularJS and Onsen/Monaca UI. In my app, I have a feature that detects button clicks and after a certain number of clicks, the user is directed to a confirmation screen. However, if the user takes too long to mak ...

jQuery unable to target Bootstrap button

I've been experiencing some trouble trying to attach a listener to a button I made with Bootstrap. <button type="button" id="buttonone" class="btn btn-default btn-lg good"> <span class="glyphicon glyphicon-minus" aria-hidden="true">< ...

Extremely sluggish updating efficiency

As I parse through a CSV file, I aim to verify if the corresponding entry exists in the database for each row. If it does exist, I want to update it; if it doesn't, I want to create a new entry. The process seems to be sluggish, averaging only around ...

contrasting the application of logic in Rails controllers versus JavaScript within the .js.erb files

When dealing with a large "data" active record object that needs to be filtered based on user interactions on a page, the question arises about where to place the data-filtering logic. Currently, the filtering is done in the rails controller action, simpli ...