How can you use a MongoDB query to count the number of documents containing a specific array index that is stored in a JavaScript variable

Looking at my dataset, it appears as follows:

{
"_id" : ObjectId("58efcbb9ac808c5c0771b1b0"),
"guid" : "cda474b9-1362-4ffe-99df-5c0783fff8be",
"g" : "SomeString",
"m" : "Something else",
"r" : null,
"dh" : ISODate("2017-04-13T19:00:00.000Z"),
"ei" : 60000,
"v" : [ 
    {}, 
    {}, 
    {}, 
    {}, 
    {
        "last" : 0.0,
        "sum" : 0.0,
        "cnt" : 1,
        "minimum" : 0.0,
        "maximum" : 0.0
    }, 
    {}, 
    {}
]

}

There are many entries similar to the one above. In the case of a specific "guid," there could be around 100 entries like the one shown. My goal is to count the number of entries where the guid is equal to SOMEGUID and the "cnt" element exists at a particular index within the array.

The challenge lies in the fact that the array index is stored in a variable, and it is derived from another source.

This line of code works effectively:

print(myguid + ": " + db.MyCollection.find({"guid" : myguid, "v.4.cnt" : { $exists : true}} ).count());

This produces output similar to:

2e605c07-54b2-49e6-8a9f-f31d3dffe57c: 28

The issue I am facing is that I do not wish to hardcode "4" in the query. I have the index saved in a variable named arrayIndex, and I aim to include it in the query.

An attempt like the following does not yield the desired result:

print(myguid + ": " + db.MyCollection.find({"guid" : myguid, "v.arrayIndex.cnt" : { $exists : true}} ).count());

Any assistance on this matter would be greatly appreciated.

Answer №1

If you want to include an index in your JavaScript code, you can use the following approach.

function calculateTotal(myID, index) {
    const query = {"id": myID};
    query["v." + index + ".total"] = {$exists: true};

    return db.MyCollection.count(query);
}

This function will create a query for a specific index and count the total number of objects.

Usage example:

calculateTotal("some-id", 3);

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

The JavaScript functions are not loading within the onload event handler

I've got an HTML document that contains some Script sections. I've consolidated all the functions within a single Script Tag. Now, I want to be able to utilize these methods in both the onload and onclick events. Below is the HTML file with all t ...

Angular JS element cannot be located

My Angular object is not being passed when I write a new function, and I'm unsure why. The object, named person, is directly bound in the HTML and returns 2 items from the cardsCollection array. The function I'm attempting to create is called cl ...

Navigating through the content of slots within recurring slots in a subcomponent in Vue.js

I am encountering an issue with a child component, where each row in an object is rendered inside a div with a specific slot. I need to pass data from the parent for each of these elements. I've been attempting to iterate through every element of the ...

I am experiencing an issue with using double quotation marks in VS Code

Whenever I press the double quote symbol like this "", the cursor automatically moves to the end. While this may be natural, I would prefer the cursor to move inside the double quotes automatically when pressing them. Additionally, it's a bi ...

Make sure to update the package.json file at multiple locations following the execution of the "npm i" command

My goal is to automatically detect any newly installed packages based on my package.json file. This way, whenever I run "npm i", the new package will be added not only to the usual "dependencies" section but also to a custom section called "extDependenci ...

Error in the delete function on a JSF webpage

I am currently working on implementing a JSF table with a delete button. Below is the JavaScript code that triggers the dialog box: function showDialog(a){ $("<div />", { text: a }).dialog({ width: 600, ...

The javascript file does not load and stringByEvaluatingJavaScriptFromString is also not running?

In my application, I am downloading an HTML file from the server and displaying it in a uiwebview. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths firstObject]; NSStri ...

Navigating with React in ES5

My email addresses are "[email protected]" and "[email protected]". I am facing an issue with the following minimal example code: var React = require('react'); var ReactDOM = require('react-dom'); var Router = require(' ...

Choose options from an array in AngularJS using the same ng-model for a dropdown menu

I have developed a cross-platform app using AngularJS, Monaca, and OnsenUI. Within the app, there is a large form with multiple drop-down select options. The majority of these options are Yes/No selections. To handle these Yes/No options, I've creat ...

What is the best way to iterate through an array and dynamically output the values?

I am facing an issue with a function that retrieves values from an array, and I wish to dynamically return these values. const AvailableUserRoles = [ { label: 'Administrator', value: 1 }, { label: 'Count', value: ...

Issue with WebRTC, socket.io, and node.js: Unable to access the property 'emit' as it is undefined

Currently, I am in the process of creating a webrtc video app. Within the client code section, the following lines are present: getUserMedia(constraints, handlemedia, errorhandle); constraints = {video: true}; function handlemedia(stream){ //other act ...

How can I incorporate a spinning cog from Font Awesome into a jQuery click event?

I am looking to incorporate a spinning font awesome cog while the data is being fetched and remove it once the process is complete. Here is the HTML snippet that needs to be inserted: <i class="fa fa-spin fa-cog"></i> And this is the accompa ...

Steps for highlighting specific character(s) within a textarea

I am working on a program to search for specific characters within a designated <textarea> element. I want to be able to highlight or color the characters that match the search criteria within the text area. How can I achieve this effect and color th ...

How to add an OnClick listener to a cell element in a table built with the Tan

I am currently working on a project using React and trying to implement a table. I want to show an alert when a header cell in the table is clicked, displaying some information. However, I have been struggling to find assistance on adding a click listener ...

What could be causing the show button to change its style every time I click it?

I'm a beginner in the world of JavaScript. I have been working on customizing the "show more" button and encountered an issue. I managed to add text and a down arrow below the button, but when I click it, another button labeled "I don't know how ...

Leveraging ng-class for selectively applying CSS3 animations based on conditions

When specific conditions are met in my controller, I apply two CSS3 animations to the DOM using ng-class. The animations (shake Y & shake X) are added based on certain criteria being satisfied. Here is a snippet of the relevant JavaScript code: $scope.sub ...

Using Vue JS to display information conditionally within a single component

I currently have a component that dynamically displays the data from an array of objects. However, I want the component to display only one object based on a specific condition. Is it possible to show either one object or another depending on the value o ...

Handling onclick events in Scrapy Splash: A comprehensive guide

I am attempting to extract data from the following website I have managed to receive a response, but I am unsure how to access the inner data of the items below for scraping: It seems that accessing the items requires handling JavaScript and pagination. ...

The fixed element alters its color when applied to a specific class within a div

I have a button with an icon and text that remains fixed on my webpage. The background colors of the sections change as you scroll through them, alternating between dark and light. I am looking for a solution where I can apply a class to multiple section ...

How can I conceal HTML elements within a Xamarin Android WebView?

I am currently developing a web wrapper application and I want to display specific elements in an HTML page. The code snippet provided below shows my progress so far, but I understand that I may need to utilize JavaScript to achieve the desired functionali ...