How can MongoDB be used to query nested JSON structures?

My JSON data structure is as follows:

"marks":{
    "sem1" :{
        "mark1":10,
        "total":100
    },
    "sem2":{
        "mark2":20,
        "total":200
    },
    "sem3":{
        "mark2":30,
        "total":300
    }
}

I want to display the results in the following format:

mark  total   sem

10    100     sem1 
20    200     sem2  
30    300     sem3

To achieve this format, I am looking into using MongoDB and the query.query. Additionally, Jaspersoft integration seems like a promising solution for this task.

Answer №1

This particular structure may not be optimal, but if you have limited control over it, a solution involving mapReduce for JavaScript processing could be implemented:

db.collection.mapReduce(
    function () {
      var doc = this,
          marks = doc.marks;

      Object.keys( marks ).forEach(function(key) {
        //emit( key, doc["marks"][key] );
        var matched = Object.keys( marks[key] ).filter(function(inner) {
          return inner.match(/^mark/);
        });

        if ( matched.length > 0 ) {
          //emit( matched[0], 1 );
          var myMatched = matched[0];
          emit(
            marks[key][myMatched], {
              total: marks[key].total,
              sem: key
            }
          );
        }
      });
    },
    function() {}, // null reducer not required
    { "out": { "inline": 1 } }
);

While not directly achieving the desired output, the above approach illustrates how mapReduce can handle such structures that are not easily queryable or analyzable through traditional methods.

A more efficient solution would involve reformatting the data like so:

{
    "marks": [
        { "semester": "sem1", "mark": 10, "total": 100 },
        { "semester": "sem2", "mark": 20, "total": 200 },
        { "semester": "sem3", "mark": 30, "total": 300 }
    ]
}

To query this revised structure, utilize the aggregation framework which utilizes native code to traverse the data without relying on JavaScript notation:

db.collection.aggregate([
    { "$unwind": "$marks" },
    { "$project": {
        "mark": "$marks.mark",
        "total": "$marks.total",
        "sem": "$marks.semester"
    }}
])

Further customizations can be made based on specific analysis requirements and objectives within the given dataset.

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

Unable to use onSubmit with enter key in render props (React)

I am looking to include a button within a form that can trigger the onSubmit event when the user presses the Enter key. Here is an example of a functional solution: <form onSubmit={() => console.log('ok')}> <button type="submi ...

Issues with managing multiple user sessions in express-session

I've been struggling with an issue for a few days now and haven't been able to find a solution. I've scoured forums and documentation, but nothing seems to work. I have a website built in Node.js, using express-session and passport for sessi ...

Send information to a function until the array reaches its maximum length

I am facing a challenge where I have a function that accepts multiple arrays as arguments, but the data available to me is already within an array called mainArr. This mainArr consists of several array items that need to be passed as arguments to the funct ...

A guide to incorporating border radius to images within a composite image with sharp.js in Node.js

In my Node.js project, I am using the sharp library to combine a collection of images into a single image. Although I have successfully created the composite image, I now need to add a border radius to each of the images in the grid. Here is the code snip ...

Encountering a Next.js installation error due to the inability to locate the module fs

Having trouble with the installation of a new Next.js 14 app. I've searched on Google and Stack Overflow but haven't been able to find a solution. I'm stuck at this point. Can anyone offer some assistance? What I have attempted: npx creat ...

Accessing a Variable in one JavaScript File from Another JavaScript File

In the process of creating a basic game using only JavaScript and jQuery, I have split it into two separate pages. The first page contains all the rules and necessary information, while the second page is where the actual game takes place. My goal is to in ...

Upon attempting to utilize Socket.io with Next.JS custom server, the server repeatedly restarts due to the error message "address already in

Every time I attempt to execute the refreshStock() function within an API endpoint /api/seller/deactivate, I encounter the following error: Error: listen EADDRINUSE: address already in use :::3000 at Server.setupListenHandle [as _listen2] (net.js:1318: ...

Implementing route navigation in two components using a click button

To display the content of the Quiz component with the path "/quiz" after clicking a button and fetching the component with the path "/" is my goal. Here is the code snippet from the App.jsx file: <Router> <Routes> <Route ...

Tips for avoiding axios from making a post request before the state is properly updated

I'm encountering an issue where the post request doesn't send the updated currentVideo state because setState appears to be non-blocking. Is there a way to make axios wait for the state to be set before making the post request? const nextVideo = ...

The mobile menu is not responding to the click event

Upon clicking the mobile menu hamburger button, I am experiencing a lack of response. I expected the hamburger menu to transition and display the mobile menu, but it seems that neither action is being triggered. Even though I can confirm that my javascrip ...

The HTML content retrieved through an ajax service call may appear distorted momentarily until the JavaScript and CSS styles are fully applied

When making a service call using ajax and loading an HTML content on my page, the content includes text, external script calls, and CSS. However, upon loading, the HTML appears distorted for a few seconds before the JS and CSS are applied. Is there a sol ...

Creating a new component when a click event occurs in React

Currently diving into the world of React while working on a project that involves mapbox-gl. I'm facing an issue where I can successfully log the coordinates and description to the console upon hover, but I can't seem to get the popup to display ...

What is the best location to specify Access-Control-Allow-Origin or Origin in JavaScript?

After researching, I found out that I need to set my Access-Control-Allow-Origin or Origin tags. But the question is: where do I actually add these? The suggestions were to use them in the header section. I couldn't find any detailed explanation on t ...

What could be causing the mousewheel event in my code to remain active?

Whenever I try to scroll on Google Chrome, an error occurs on my website. jquery-3.3.1.min.js:2 [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See To resolve this issue: $(document).ready(f ...

Execute code when a specific event is being attached in jQuery

When using JQuery, custom events such as .bind("foo", function(e)... are well-supported. But what if the event triggering mechanism is not yet prepared and needs to be created only on elements with the event already bound? For instance, let's say I w ...

How to Use MongoDB Aggregation to Filter Data Based on Two

When an aggregation pipeline stage is executed, it generates the following collection: { _id : { airport : "SGF", minEffect : "security_delay", delayType : "arr_delay", } } { _id : { ...

Establishing connectivity between an AngularJS application and Mongodb by utilizing NodeJS

I have implemented an AngularJS application that successfully retrieves data from an array in a controller using ng-repeat. Now, my goal is to integrate it with Mongodb through NodeJS so that the app can fetch data from a Mongodb collection. Additionally, ...

What is the best way to access the rendered child components within a parent component?

I am seeking a way to retrieve only the visible child components within a parent component. Below is my unsuccessful pseudo-code attempt: parent.component.html <parent (click)="changeVisibility()"> <child *ngIf="visible1"></child> ...

Node.js is having trouble locating the JSON file for Ajax requests

Currently, I've developed a fun little game using the p5.js library and wanted to integrate a Leaderboard feature that pulls data from a JSON file acting as a database to store Usernames and scores. To achieve this, I've utilized a Node.js server ...

What is the best way to gather user input and incorporate it into a selected template, ensuring it is verified before sending?

I'm in the process of developing a project that involves gathering user input through a collector and displaying it on my template for verification before sending it out. The format I'm aiming for can be seen here: This is the template format I ...