What is the best method for combining values from two separate results in MongoDB?

These are the results of two queries that I conducted.

First Query

db.game.aggregate( [ 
{ $group : { _id : "$HomeTeam", shots: { $sum : "$HS" } } },
{ $sort : { shots : -1 } }
])

Results of First Query

{ "_id" : "Man City", "shots" : 386 }
{ "_id" : "Liverpool", "shots" : 335 }
...

Second Query

db.game.aggregate( [ 
{ $group : { _id : "$AwayTeam", shots: { $sum : "$AS" } } },
{ $sort : { shots : -1 } }
])

Results of Second Query

{ "_id" : "Man City", "shots" : 297 }
{ "_id" : "Chelsea", "shots" : 281 }
...

I am now looking to create a query that combines and adds up the shots from both queries for the same team. For example:

{ "_id" : "Man City", "Totalshots" : 683 }

Answer №1

  • $facet is used to segregate the results for both HS and AS fields
  • $project helps in merging both arrays into a single array by utilizing $concatArrays
  • $unwind breaks down the result array
  • $group groups by _id and calculates the sum of shots
  • $sort arranges by shots in descending order
db.game.aggregate([
  {
    $facet: {
      HS: [
        {
          $group: {
            _id: "$HomeTeam",
            shots: { $sum: "$HS" }
          }
        }
      ],
      AS: [
        {
          $group: {
            _id: "$AwayTeam",
            shots: { $sum: "$AS" }
          }
        }
      ]
    }
  },
  { $project: { result: { $concatArrays: ["$AS", "$HS"] } } },
  { $unwind: "$result" },
  {
    $group: {
      _id: "$result._id",
      Totalshots: { $sum: "$result.shots" }
    }
  },
  { $sort: { Totalshots: -1 } }
])

Mongo Playground

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

Setting up a simple NPM and Gulp configuration

I've decided to streamline my front-end development process, so I kicked it off by bringing in all the necessary dependencies using NPM. Let's take a peek at my package.json: "main": "main.js", "dependencies": { "jquery": "^2.1.4", "vue": "^ ...

how to dynamically adjust the width of chart bars in Reactjs

As a newcomer to ReactJS, I feel like there is something I am missing in my understanding. I am working on filling charts based on the percentage of the variable lista. My goal is to have the value fit within the width of the div (line 70 in the component& ...

Access the specific scope I established in Angular console, excluding the entire scope

Is there a way to access only the $scope elements (variables and functions) created in my controller without getting everything ($$childTail, $$childHead, etc)? I know if I use: angular.element(document.querySelector('<selector-name>')).sc ...

What is the connection between React and referencing a blob in a canvas

Looking for a way to convert a canvas element into a blob in React for printing with a local printer. The focus is on the technique rather than the specific printer-related code. The canvas as a React element prints successfully, indicating that the issue ...

Creating an MPG4 Video from a Three.js Scene: What Are the Steps?

I am working with a three.js scene that includes numerous animated objects. I am looking to export this animation as an mpg4 video. Here are my questions: What is the best method for exporting a scene to create an mpg4 video? Is it recommended to perfo ...

Looking to showcase the current operating hours for today?

It would be great to feature a box on our upcoming library website showing the operating hours for that day. This way, visitors can easily see when the library is open each day they visit the site. Additionally, I plan to include a link for more extensive ...

Sending a POST request to Mailchimp via Express using React: A step-by-step guide

I'm currently working on a project where users can sign up for a new membership through a form in React and have their information added to the Mailchimp member list via my Express server. However, I've encountered a CORS error and am unsure if I ...

The following MongoDB errors unexpectedly popped up: MongoNetworkError: connect ETIMEDOUT and MongoServerSelectionError: connect ETIMEDOUT

I've been working on a React and NextJS App for about a month now, utilizing MongoDB as my database through MongoDB Atlas. I'm currently using the free version of MongoDB Atlas. For the backend, I rely on NextJS's api folder. Everything wa ...

Changing the direction of the cursor to move opposite of the mouse's input

I'm currently working on a unique webpage with an unconventional navigation method. The concept involves the cursor moving in the opposite direction of mouse movement input. To achieve this effect, I decided to hide the actual cursor and use JavaScri ...

Determine if a generated number matches the previous one using Javascript

On my webpage, I have multiple tiles that are being manipulated with JavaScript to switch a class on a random tile every 2 seconds. I am interested in implementing a check so that the same tile is not toggled twice consecutively. I attempted the followin ...

Generate an asynchronous boolean promise when calling the isPresent function in Protractor

I'm currently working on a function that checks the presence of an element and returns a boolean value accordingly. However, I am facing an issue where the response includes unnecessary information. the output displays: false How can I adjust my cod ...

Locates every document where an array field includes a document that meets specific criteria

I am currently working with a MongoDB collection that stores all user data. Each document in my collection is represented in JSON format as follows: { "_id" : ObjectId("542e67e07f724fc2af28ba75"), "id" : "", "email" : "<a href="/cdn-cgi/l/ ...

When a new entry is added to the database, automatically refresh a <div> section within an HTML document

I have a basic webpage that showcases various products stored in the database. My goal is to implement an updater feature where, if a user adds a new product, the page will automatically display the latest addition in a specific div. I attempted to refere ...

Can you help me figure out how to convert checkbox inputs into a JSON array?

As a newcomer to .js, I am facing an issue with extracting responses from a .js checkboxes form and converting them into a JSON array. Here is my HTML structure: <form> <input type="checkbox" name="Question1" id="Answer1" value="Answer1" onclick ...

Trouble with escaping characters in Javascript?

My code looks like this: `message.channel.send( const Discord = require('discord.js'); const client = new Discord.Client(); const token = 'your bot token here'; client.on('ready', () => { console.log('I am ready!& ...

I am experiencing an issue with the Search Filter where it is not successfully removing

My goal is to filter colors when a user searches for a color code. Currently, the search function displays the correct number of filtered items, but the color bubbles are not being removed as intended. I am working on removing the bubbles when a search is ...

Having trouble retrieving the desired information within the JSON format. What exactly is the discrepancy between the two sets of data?

I've researched extensively on similar issues but have not been able to find a solution. My goal is to retrieve the name and value of a coin. The Coinmarketcap API has 2 endpoints. The first endpoint, as indicated in the comment, provides the desired ...

Tips for configuring a function to only be called once, even when the page is reloaded

I'm currently facing an issue with making a Post request upon component Mount. Every time the user reloads the page or there's a change in state, the function gets called again due to the useEffect hook, resulting in multiple requests being sent. ...

Selecting Elements in AngularJS with jqLite while Excluding a Specific Element: What You Need to Know

Currently, I am in the process of developing a directive to manage a side menu within a mobile application. The menu opens smoothly with the directive I've implemented, but I am facing a challenge in selecting everything except the menu using jqLite. ...

Encountering a bizarre error while setting up Vue with end-to-end testing

Every time I try to create a project using vue create, I keep getting the same error message: ✨ Creating project in C:\Users\.... ⚙️ Installing CLI plugins. This might take a while... npm ERR! Unexpected end of JSON input while parsing n ...