Summarizing and Aggregating data in MongoDB using General Summation and Unique Key Summarization

If we consider a database of sold cars from a dealership, each represented by an object with various properties such as model, carId, and salesmanId, how can we efficiently query the total number of cars and unique car models per salesman? Let's look at an example dataset:

{
 id: 'randomId',
 model: 'Jetta',
 carId: 'randomId',
 salesmanId: 'salesmenId3'
},
{
 id: 'randomId',
 model: 'Civic',
 carId: 'randomId',
 salesmanId: 'salesmenId2'
},
{
 id: 'randomId',
 model: 'Civic',
 carId: 'randomId',
 salesmanId: 'salesmenId2'
},
{
 id: 'randomId',
 model: 'S200',
 carId: 'randomId',
 salesmanId: 'salesmenId'
},
{
 id: 'randomId',
 model: 'Jetta',
 carId: 'randomId',
 salesmanId: 'salesmenId3'
},
{
 id: 'randomId',
 model: 'Civic',
 carId: 'randomId',
 salesmanId: 'salesmenId2'
},
...

When querying for a specific salesmanId, like 'salesmenId2', we would expect a result like this:

{
 salesmanId: 'salesmenId2',
 totalCars: 3,
 totalUniqueCars: 1
}

The initial approach to this query involves $match to filter by salesmanId, $group to group by salesmanId and calculate totalCars, and $addToSet to create a list of unique cars. However, the query as it stands currently only returns the total of unique cars. What could be missing in the query logic?

Answer №1

Forget about using the $unwind function, why not try utilizing the $size operator on the "uniqueCars" array field? This operator will provide you with the size of the array, making your task much easier.

 db.cars.aggregate([
    {
        $match: { "salesmanId":  "salesmenId2" } 
    }, 
    {
        $group: {
                    _id: "$salesmanId",
                    uniqueCars: { $addToSet: "$model"},
                    totalCars: { $sum: 1 }
                }
    },
    { 
       $project : { 
                     _id : 1, 
                     totalCars : 1, 
                     uniqueCar : { $size : "$uniqueCars" }
                  }
    }
 ])

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

Trouble shooting: Angular 2 Http get request not firing

I'm facing an issue where nothing happens when I try to subscribe to my observable. There are no errors in the console or during the build process. Below is the code snippet that I am using: My service getBlueCollars(): Observable<BlueCollar[]& ...

I am encountering an issue with my ui-router resolve where it is not returning any information despite no

I am struggling to connect my MongoDb and API REST with my Angular application. It seems like there is an issue with resolution. Currently, I am following a MEAN application tutorial on this website. This snippet shows my ui-router configuration. var ap ...

Transitioning the Background Image is a common design technique

After spending hours trying to figure out how to make my background "jumbotron" change images smoothly with a transition, I am still stuck. I have tried both internal scripts and JavaScript, but nothing seems to work. Is there any way to achieve this witho ...

I'm having trouble understanding why my Javascript validation suddenly stopped functioning. Can anyone assist me in troubleshooting this issue?

I have been working on this webpage for a school project for a few days, and it was running smoothly until about 10 minutes ago. The only change I made was adding an extra JavaScript validation. Now, when I try to register by clicking the "register" butt ...

Using the TIMESTAMP data type in PostgreSQL and getting the most out of it

After saving a Luxon datetime value in a TIMESTAMP(3) type column in a postgres database, I encountered difficulty using it for various operations like converting time zones. Despite creating the object with the code snippet below: const { DateTime } = req ...

Trigger functions when the window is scrolled, resized, or when the document is fully loaded

I have a few functions that need to be executed under specific conditions: window.scroll window.resize document.ready For example: <script> function myFunction1(data){ /*code*/ } function myFunction2(data){ /*code*/ } ...

Unable to set a value for the variable

const readline = require('readline'); let favoriteFood; const rl = readline.createInterface(process.stdin, process.stdout); rl.question('What is your favorite food?', function(answer) { console.log('Oh, so your favorite food is &a ...

Define a universal URL within JavaScript for use across the program

When working with an ASP.NET MVC application, we often find ourselves calling web service and web API methods from JavaScript files. However, a common issue that arises is the need to update the url in multiple .js files whenever it changes. Is there a me ...

Utilizing React Hooks and Firebase Firestore onSnapshot: A guide to implementing a firestore listener effectively in a React application

SITUATION Picture a scenario where you have a screen with a database listener established within a useEffect hook. The main goal of this listener is to update a counter on your screen based on changes in the database: (Utilizing the useEffect hook without ...

The Mongoose findOneAndUpdate function is failing to save data to MongoDB

I have integrated Mongoose into my codebase to connect with a MongoDB database specifically for Discord bots. My goal is to update the value of the Boolean activated to true in the database if the user possesses a certain role. Despite having no errors w ...

Fastify Schema Failing to Validate Incoming Requests

Currently, our backend setup involves using Node.js and the Fastify framework. We have implemented a schema in satisfy to validate user input. Below is the schema defined in schema.ts: export const profileSchema = { type: 'object', properti ...

Update the content on the webpage to display the SQL data generated by selecting options from various dropdown

My database table is structured like this: Name │ Favorite Color │ Age │ Pet ────────┼────────────────┼───────┼─────── Rupert │ Green │ 21 │ ...

Tips on editing a file exclusively when a specific requirement is fulfilled

Looking for a way to implement a put method within an Express API that allows users to update a document conditionally? Consider this scenario: you have an Instance document with an attribute called executed, which is set to true if the instance has been e ...

Encountering a 422 ERROR while attempting to send a POST request

Below is the code snippet I am currently using: const url = new URL("https://api.chec.io/v1/products"); const headers = { "X-Authorization": `${process.env.NEXT_PUBLIC_CHEC_PUBLIC_KEY_SECRET}`, "Accept": "appl ...

What advantages does JWT have over Firebase that make it the preferred choice?

In our authentication systems, we have the option to verify a user through Firebase or by their stored email in the database. Despite having these methods of verification, why do we incorporate JWT (json web token) into our processes? What distinct advan ...

Using Jquery and AJAX to dynamically fill out an HTML form based on dropdown selection

My goal is to populate a form on my webpage with information pulled from a MySQL database using the ID of the drop-down option as the criteria in the SQL statement. The approach I have considered involves storing this information in $_SESSION['formBoo ...

I am interested in extracting information from the Firebase real-time database and showcasing it on my HTML webpage

I am struggling to display data from the Firebase real-time database on my HTML page. Even though I can see all the data perfectly in the console, it doesn't show up on the webpage. I attempted to use a for loop, but it still doesn't display the ...

I would like to learn how to style my React component by adding borders to the table, as well as the tr, th, and td elements

I am trying to apply borders to the tr, th, and td elements within a styled component div that already has a border applied to the table element. Here is the current code I have: The styled component const Skill1 = styled.div` border: 1px solid black; &g ...

To set up MongoDB on your system, execute the following command: `npm install --

I've encountered a problem while attempting to install MongoDB on my personal computer for a Node project. I used the command line and ran npm install --save mongodb. Even though MongoDB appears in the dependencies section of my package.json file with ...

The management of jQuery events through .on and .off functions, maintaining the correct order, and ensuring their

Check out this jsFiddle example: http://jsfiddle.net/fThMa/2/ By clicking inside the note or rend text fields and then double clicking any of the 4 TDs below, you can insert the appropriate HTML entities into the note or rend text fields. This also includ ...