Retrieving arrays in subdocuments with MongoDB queries

Being a novice in the realm of mongodb, I welcome any corrections if my terminology is incorrect:

The document snippet below showcases some information:


{
    "_id" : ObjectId("524b0a1a7294ec8a39d4230f"),
    "name" : "Irbesartan",
    "decompositions" : [
            "IRB_444",
            "IRB_442",
            "IRB_446",
            "Valsartan acid"
    ],
    "precursor" : [
            {
                    "mass" : 429,
                    "ion" : "+H",
                    "charge" : "+",
                    "fragments" : [
                            207,
                            195,
                            180
                    ]
            },
            {
                    "mass" : 427.2252,
                    "ion" : "-H",
                    "charge" : "-",
                    "fragments" : [
                            193,
                            399
                    ]
            }
    ]
}

Upon executing

db.substances.findOne({name: "Irbesartan"}).precursor

The following data is retrieved:

[
    {
            "mass" : 429,
            "ion" : "+H",
            "charge" : "+",
            "fragments" : [
                    207,
                    195,
                    180
            ]
    },
    {
            "mass" : 427.2252,
            "ion" : "-H",
            "charge" : "-",
            "fragments" : [
                    193,
                    399
            ]
    }
]

I am interested in accessing the fields within, particularly the fragment array (using Mongo Shell)

Is achieving this in a single query possible?

Or would it be more advantageous to store the precursor as an array rather than a subdocument?

Answer №1

Here is an example query:

db.substances.distinct("precursor.fragments", {name: "Irbesartan"})

The result of the above query is:

[ 180, 193, 195, 207, 399 ]

Alternatively, you can use the following query:

db.substances.findOne({name: "Irbesartan"}).precursor.map(function(r) {
  return r.fragments;
})

This alternative query yields:

[ [ 207, 195, 180 ], [ 193, 399 ] ]

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

Combining elements from a string array to create a hierarchical object in JavaScript

I need assistance with merging values from an array into a predefined nested object. Here is an example of the array with values, ['name=ABC XYZ', 'hobbies=[M,N,O,P]', 'profession=S', 'age=27'] The object that needs ...

Using jQuery to dynamically populate a list with the information from a JSON dataset

How can I utilize JSON data to ensure that jquery populates the correct ul in this code snippet, creating 5 ul and populating them with li elements? Expected output: The slides should be assigned to specific modules as indicated in the JSON data, instead ...

Fixing JQuery Promise Failure in React.JS ComponentDidMount

When utilizing the ComponentDidMount life cycle method in my components, I encountered an issue with an AJAX request. Despite successfully retrieving data, the promise chain kept deferring to the fail property. This puzzling behavior persisted even when I ...

Traversing through an array and populating a dropdown menu in Angular

Alright, here's the scoop on my dataset: people = [ { name: "Bob", age: "27", occupation: "Painter" }, { name: "Barry", age: "35", occupation: "Shop Assistant" }, { name: "Marvin", a ...

Tips on accessing the text content of a dt element with prototype

Below is some HTML code that I am working with: <dl> <dt><label>test</label></dt> <dd><input id="someid" type="checkbox" onchange="opConfig.reloadPrice()" class="product-custom-op ...

Using ESM imports in webpack configuration

I'm in the process of creating a webpack application and I am keen on utilizing ESM (ECMAScript Modules) throughout the entire project. This involves configuring the webpack.config file to allow for ESM imports. Previously, I knew that this could be ...

Getting the URL path within getStaticPaths in Next.js

Is there a way to retrieve the last number from the current URL pathnames in getStaticPaths? http://localhost:3000/category/food/2 -> 2, http://localhost:3000/category/food/3 -> 3, ... I have attempted: export const getStaticPaths: GetStaticPaths = ...

jQuery is optimized to work specifically with select id tags

Here is the HTML code snippet I've put together, along with my script. While I admit it might look a bit messy, please bear with me as I'm still in the learning phase. If anyone could offer some assistance on this matter, I would be extremely gra ...

Optimizing Node Docker Build and Production Container Strategies

Currently, I am working on a Node project that utilizes MongoDB. In order to conduct automated testing, we have implemented the use of Mongo Memory Server. However, we have encountered an issue where Mongo Memory Server does not support Alpine, therefore ...

Steps for inserting API data into a MySQL database

I am currently working on a project and need help figuring out how to integrate my API results into MySQL. You can find the results on this page. Below is the code snippet from the page: <?php ///PLOT PROJECT USER REQUEST //FUNCTION TO DEBUG IN ...

Running Javascript code to perform drag and drop in Selenium for UI integration testing in Java

I am currently working on a task involving writing UI test cases (Automation) using Selenium in Java. I have an HTML page with an element that needs to be dragged to a target. Despite trying the Action functionality in Selenium, it didn't work for me. ...

Issue compiling Mongodb with C++

I'm currently attempting to compile the mongodb driver for C++ by following the instructions provided on the following link: Mongocxx However, I am encountering the following errors: -- The CXX compiler identification is GNU 4.8.5 -- Check for worki ...

Display a division in C# MVC 4 when a boolean value is true by using @Html.DropDownList

I have multiple divs stacked on top of each other, and I want another div to appear when a certain value is selected. I'm familiar with using JavaScript for this task, but how can I achieve it using Razor? Below is a snippet of my code: <div id=" ...

Best practices for avoiding string concatenation in Oracle-db with Node.js

Is there a way to prevent SQL injection caused by string concatenation in the SQL query? The searchParameter and searchString parameters, which come from a GET request, are optional. They should be added to the WHERE clause to filter results based on user ...

What is the best way to change an array element into a string in TypeScript?

Within my Angular 2 component, I am utilizing an array named fieldlist which is populated by data retrieved from an http.get request. The array is declared as follows: fieldlist: string[] = []; I populate this array by iterating through the JSON response ...

Having difficulty replicating the sorting process in Vue.js for the second time

I need assistance with implementing sorting functionality in a Vue.js table component. Currently, the sorting mechanism is working fine on the first click of the th item, but it fails to sort the items on subsequent clicks. const columns = [{ name: &ap ...

What prevents me from changing the component's state while inside a useEffect callback?

I have been working on creating a timer that starts running when the app is in the background, and then checks if it has been 15 minutes (for testing purposes, I am using 15 seconds). If the time limit is crossed, the app logs the user out, otherwise, the ...

Syntax error triggered and caught by ajaxError

I have implemented a client-side ajax error handler using the following code: $(document).ajaxError(processAjaxError); $.getJSON('/data.json'); In the server side, I have defined a function as shown below: def get(self): self.response.he ...

Validation in Angular2 is activated once a user completes typing

My goal is to validate an email address with the server to check if it is already registered, but I only want this validation to occur on blur and not on every value change. I have the ability to add multiple controls to my form, and here is how I have st ...

Refresh the Data Displayed Based on the Information Received from the API

As someone who is relatively new to React, I have been making progress with my small app that utilizes React on the frontend and a .NET Core API on the server-side to provide data. However, I have encountered a problem that I've been grappling with fo ...