Combining duplicate values in MongoDB using aggregation

In my code, I have an aggregate function that counts the occurrences of a value in the database:

  let data: any = await this.dataModel.aggregate(
      [
        {
          $match: {
            field: new ObjectID(fieldID),
          },
        },
        {
          $group: {
            _id: "$value",
            total_for_value: { $sum: 1 },
          },
        },
      ]
    );

While this solution is effective, my data structure presents a challenge. There are two types of value fields. Some are structured like this:

    {
    "_id" : ObjectId("123"),
    "value" : "MALE"
    }

and others like this:

{
    "_id" : ObjectId("456"),
    "value" : {
        "value" : "MALE",
    }
}

I need to find a way to group records where both the _id and _id.value are the same. Currently, they are being counted separately.

Answer №1

db.collection.aggregate([
  {
    "$addFields": {
      "newKey": {
        "$cond": {
          "if": {
            $and: [
              {
                "$eq": [
                  {
                    "$type": "$key"
                  },
                  "object"
                ]
              }
            ]
          },
          "then": "$key.value",
          "else": "$key"
        }
      }
    }
  },
  {
    "$group": {
      "_id": "$newKey",
      "data": {
        $push: "$$ROOT"
      }
    }
  }
])

This code snippet is designed to work when _id.value represents an object.

Access the Playground 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

Ways to insert HTML text into an external webpage's div element without using an iframe

Is it possible to generate HTML and SVG code based on the position of a Subscriber on a web page or within a specific div? I would like to provide some JavaScript code that can be inserted inside a particular div on the page. Using an iframe is not ideal ...

EJS selectively displaying certain elements from an object

This particular issue has been baffling me. I have been passing an object into an ejs template and when I output that object, everything appears as expected: { _id: 5504a5e7ff67ac473dd7655c, code: 'GB', name: 'United Kingdom', slug: & ...

Omit specific files from $geoNear query results

I am managing two different collections named Cards and Swipes. Users have the ability to request a list of cards and swipe on them. Once a card is swiped, I want to ensure that it does not reappear in the list, meaning I only want to show cards that have ...

Transform Dynamic Array to JSON structure

I am currently developing a feature in my SvelteKit application that allows users to create custom roles for themselves. Users can input a role name and add it to an array, which is then displayed below. https://i.stack.imgur.com/oUPFU.png My goal is to ...

Modifying the height of the bar in Google Charts Timeline using react-google-charts

I am currently working on a Google Chart timeline using react-google-charts. <Chart chartType="Timeline" data={data} width="100%" options={{ allowHtml: true bar: { groupWidth: 10 }, }} ...

Engage with Vue.js and traditional JavaScript (plain) in your projects

Exploring the integration of Vue with regular JavaScript has presented a challenge. While some solutions online propose moving all functions to a Vue component, this approach proves impractical for complex or large functions. The task now is finding a way ...

"Creating a custom input tag in Rails that triggers an event when the value is changed

Is there a more efficient way to trigger events when the value of an input tag changes (i.e., whenever a character is entered or deleted) and display these values in the controller without relying on ajax? Currently, my approach involves implementing a Ja ...

As the second line of Javascript code is being executed, the first line is still

I have a task where I need to execute a SQL SELECT statement and save the results. Then, those results need to be passed into a function to generate a graph using the data points provided. Refer to the code snippet below for details. var dataKWhr = getCov ...

Web Audio API functions are encountering a playback issue on iOS 13.3, despite working smoothly on previous iOS versions

I have been developing an audio visualizer using the web audio API. It was functioning smoothly on PC, however, after upgrading to iOS 13.3, it no longer operates on Apple mobile devices. The root cause of this issue remains a mystery to me. The problem s ...

Developing a quiz using jQuery to load and save quiz options

code: http://jsfiddle.net/HB8h9/7/ <div id="tab-2" class="tab-content"> <label for="tfq" title="Enter a true or false question"> Add a Multiple Choice Question </label> <br /> <textarea name ...

Anticipating the completion of post requests

I am currently working on implementing a file upload feature in Angular. I have tackled the issue of file size restrictions by creating an API endpoint that can receive file chunks. Once all the chunks are received, another endpoint needs to be triggered ...

Mastering angle calculations in three.js

My current task involves creating a series of arcs using 102 lines (start point, endpoint, and 100 curve points) However, I'm facing an issue when the start point of an arc has a higher value than the end point. For instance: Start Point: 359 End ...

The Lenis smooth scrolling feature (GSAP) is not functioning properly

I have encountered an issue with the smooth scrolling feature of gsap causing a delay on my website. This problem is only resolved when I manually go into the browser settings and disable smooth scrolling by navigating to chrome://flags/#smooth-scrolling ...

Is there a way to automatically clear the text field value after submitting?

Greetings everyone, I'm looking for guidance on removing the text field content once I click submit. I have a button labeled "senden" and my goal is to clear the text fields and uncheck the checkbox after clicking this button. I've attempted se ...

Creating mutual reactivity between two inputs in Vue.js

I am in the process of creating a tool that calculates the cost of purchasing specific materials. One challenge I'm facing is that users sometimes buy by mass and other times by volume. My goal is to have two active input fields (one for mass and one ...

What is the best way to integrate JQuery URL in Joomla components?

Can anyone show me how to load a jquery URL in Joomla (Component)? I have a button that, when clicked, will reload the page and use the GET method to display a value from a variable. JavaScript: jQuery("#btnclickme").click(function(){ jQuery("#divpro").l ...

Exploring the functionality of the JavaScript Date constructor in relation to

Will using new Date('2015-01-01') provide me with the exact moment equivalent to 2015-01-01T00:00:00Z? ...

Preventing undesired form submissions in HTML and JavaScript

My question might be simple, but it's what I have in mind. When working with two buttons in HTML - one for form submission and the other to trigger a JavaScript event - both buttons end up submitting the form. How can I make sure the second button onl ...

Tips on concealing confidential keys within a React.js application on the frontend aspect

Desperate times call for desperate measures - I am attempting to conceal a secret key within my React frontend application. While I understand the risks involved, I feel compelled to do so without any other viable options. The reason behind my actions is ...

Include an additional icon without replacing the existing one on the mouse cursor

I am looking for a way to enhance the user experience by adding an icon that appears when hovering over an HTML element, serving as a subtle hint that the user can right-click. Instead of replacing the default cursor, which varies across platforms and doe ...