Struggling with the nested array of objects

I have utilized Mongodb aggregation and used the $facet operator to count each value of "reli" and "prov" from the collection.

Here is the code I used to retrieve results from the database:

const keyy = await db.aggregate([
 $facet: { "reli": [
  { $group: { _id: '$reli', count: { $sum: 1 } } } ],
"prov": [
 { $group: { _id: '$prov', count: { $sum: 1 } } }
            ],
])

The output appears as follows:

 [
    {
            "reli": [
                        {
                            "_id": "abcdef",
                            "count": 6
                        },
                        {
                            "_id": "ghij",
                            "count": 1
                        },
                    ],
    
            "prov": [
                    {
                        "_id": "hello",
                        "count": 63
                    },
                    {
                        "_id": "hey",
                        "count": 9
                    },
                   ]
     
    
    }
    ]

However, I desire that the expected output should be:

 [
    {
            "reli":[
              {abcdef: 6},
              {ghij: 1}
                 ],
    
           "prov":[
              {"hello": 63},
              {"hey": 9}
                 ]
            
    }  
    ]

Answer №1

To iterate through and create a new array with specific values, you can use $map and $arrayToObject in the following way:

This code snippet demonstrates how values of reli and prov are replaced with the output of the map function. The result is an array composed of objects where the key k represents the _id value and the value v represents the count value.

db.collection.aggregate([
  {
    "$project": {
      "reli": {
        "$map": {
          "input": "$reli",
          "in": {
            "$arrayToObject": [
              [
                {
                  k: "$$this._id",
                  v: "$$this.count"
                }
              ]
            ]
          }
        }
      },
      "prov": {
        "$map": {
          "input": "$prov",
          "in": {
            "$arrayToObject": [
              [
                {
                  k: "$$this._id",
                  v: "$$this.count"
                }
              ]
            ]
          }
        }
      }
    }
  }
])

See 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

Issue with Quantity Box not displaying values in Shopify store

I am currently seeking assistance with resolving an issue I have encountered on a Shopify theme that I recently customized. The problem lies within the quantity box on the live site where despite being able to adjust the quantity using the buttons, the act ...

JavaScript (Automatic) for a full-screen webpage display

I'm having trouble creating a webpage and setting it to fullscreen mode. Here's the JavaScript code I have: var elem = document.getElementById("fulscreen"); var fs = document.getElementById("body"); elem.onclick = function() { req = fs.webk ...

Node JS Promise does not provide a value as a return

Struggling with getting a value back from the code snippet below, even though it console logs out without any issues. Any suggestions on how to assign a value to X? var dbSize = dbo.collection('Items').count() var x = 0 x = dbS ...

Tips for retrieving element height using Vue.js

I am attempting to retrieve the offsetHeight of an element but I keep getting undefined. When I use this code, it returns an HTML collection and everything works correctly: document.getElementsByClassName("plyr--full-ui"); https://i.sstatic.net/xurBa.pn ...

Creating custom directives in AngularJS can be a rewarding and powerful

When working with two directives, a situation arose where it was necessary to clear the value in Directive A by using a button located in Directive B. However, when attempting to do this using typical DOM manipulation tools like jQuery, an error occurred w ...

Discovering the potentials of decimal type implementation in MongoDB

Is there a way to save decimal values in MongoDB using the standard C# driver? It appears that all decimals are being stored as strings in the database. ...

Developing a division with an image source based on the selection of a checkbox

My goal is to develop a "change function" that generates a new div for each checked checkbox selection and removes the div when the checkbox is unchecked. These new divs should also display the img src of the selected checkbox. Currently, my JavaScript c ...

Having difficulty validating the field accurately with Angular.js

In order to validate the input field in accordance with the user's needs using AngularJS, I have shared my code below: <div ng-class="{ 'myError': billdata.longitude.$touched && billdata.longitude.$invalid }"> <input type ...

Tips on setting PropTypes for an Array containing Objects or strings

I'm currently working with a property called options, which is an array containing objects or strings. I'm looking for guidance on how to define this using React PropTypes. I recently explored the documentation at https://reactjs.org/docs/typeche ...

Implementing Knockout.js with JqueryUI Autocomplete: Access the complete object instead of just the value

I have implemented a custom binding for a JQueryUI auto complete feature that works well. However, I am looking to modify it so that it returns the Item object, which can then be pushed to another array. Can someone provide guidance on how to achieve this ...

How can we verify email addresses and URLs in PHP? Let's discuss converting this validation process

After studying the code extracted from the jquery.validate plugin, I find it quite challenging to decipher. My goal is to convert this code into PHP and I would greatly appreciate any assistance in understanding each segment of the regular expression codes ...

What is the best way to customize the link style for individual data links within a Highcharts network graph?

I am currently working on creating a Network Graph that visualizes relationships between devices and individuals in an Internet of Things environment. The data for the graph is extracted from a database, including information about the sender and receiver ...

Creating JSON arrays with JavaScript and jQuery

User Information var Users=[{"Id":1,"FirstName":"John"},{"Id":2,"FirstName":"Emily"}] Call Information var CallInfo=[{"Id":1,"PercentageCalls":"22 %","TotalTime":"60:24 minutes","PercentageTime":"0 %","AvgTime":"0:22 minutes"},{"Id":2,"PercentageCa ...

In C#, take two string arrays and copy the values from the first array to the second array, ensuring that the

I'm looking for a specific output in C#, here's what I want: A=1 C=3 D=9 e=5 If the value in the second array is 0, I do not want to include it in the output. How can I achieve this in C#? private static void Main(string[] args) { string[] ...

Pass information to CGI script and return using jQuery.ajax

Currently, I am utilizing jQuery.ajax() to transmit HTML form data from my frontend to a Perl script on the server and then receive some information back. The preferred format for this information is text or string. Additionally, I need to store it as a v ...

Is there a way to efficiently use AJAX and PHP to iterate through JSON data and save it to a new JSON file

I have created a simple movie editor with a sidebar where users can drag and drop elements. On the right side, users can edit these elements as they wish and save the data to a JSON file. When the user clicks save, I want it to create a new file and save t ...

Error in Typescript: Function not being triggered on button click

As someone who is just starting out with typescript, I've been tackling a simple code that should display an alert message in the browser when a button is clicked. I've experimented with the button and input tags, as well as using both onclick ev ...

infinite loop issue with beforeRouteEnter

I'm experiencing an issue with Vue Router. The scenario is to load / initially, retrieve data from there, and then navigate to the /chat/:chatId route to display the interface using the :chatId parameter obtained from an API. The routes configured a ...

Retrieve webpage using HTML stored in web storage

I am exploring a new idea for an application that utilizes local storage, and I am seeking guidance on the most effective way to load content after it has been stored. The basic concept of the app involves pre-fetching content, storing it locally, and the ...

Determining when props are updated in Vue.js 2 when passing an object as a prop

Let's say there is an array feedsArray, with a sample value like this: this.feedsArray = [ { id: 1, type: 'Comment', value: 'How are you today ?' }, { id: 2, type: 'Meet', name: 'Daily ...