Determine the difference between the sizes of two arrays

My current data structure looks like this:

[
  {
    name: "A",
    upvotes: [
      "a",
      "b"
    ],
    downvotes: [
      "a",
      "b",
      "c"
    ]
  },
  {
    name: "B",
    upvotes: [
      "a"
    ],
    downvotes: [
      "a",
      "b",
      "c"
    ]
  }
]

My goal is to retrieve the object with the highest number of votes. This is determined by calculating the difference between the size of the upvotes and downvotes arrays, such as

(size(upvotes) - size(downvotes))
.

For example, in this case, Object A has the highest number of votes with a calculation of ( 2 - 3 = -1).

Is there a way to achieve this using mongodb aggregation?

Thank you in advance for your assistance!

Answer №1

When running the query, a new field is added to calculate the difference between two values, then the documents are sorted in descending order based on this difference field. The query then removes the temporary difference field and returns only the document with the highest difference value.

Try the code snippet here

db.collection.aggregate([
  {
    "$addFields": {
      "diff": {
        "$subtract": [
          {
            "$size": "$upvotes"
          },
          {
            "$size": "$downvotes"
          }
        ]
      }
    }
  },
  {
    "$sort": {
      "diff": -1
    }
  },
  {
    "$unset": [
      "diff"
    ]
  },
  {
    "$limit": 1
  }
])

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

Transform Typescript into compiled css files without using any additional tools

Currently, I am working on a monorepo project where the main project relies on another project called components. When running the entire monorepo, the main project utilizes webpack.dev while the components project simply uses the TypeScript compiler. It l ...

Unable to mock ESM with unstable_mockModule

In my project, I am utilizing ESM. The transpiled .ts files are converted into .js and stored in the 'dist' directory. Here is an example of how my directory structure looks: dist/ ├─ src/ │ ├─ store/ │ │ ├─ index.js │ ├ ...

When utilizing "ng2-file-upload" in conjunction with Angular 2 and Typescript, encountering a limitation where files larger than 1MB cannot be uploaded

My attempt to upload a file with a size exceeding 1MB is triggering an error regarding its large size. Despite setting the limit to 50 MB, it doesn't seem to be working as expected. Can someone please assist me in figuring out what I am doing incorrec ...

Optimizing search queries by implementing MongoDB indexing on the IdAccount field for improved efficiency

I have been storing data in my MongoDB following a specific structure: Each customer has their own database There are around 40 collections per customer In total, there are 50 customers with approximately 2000 collections The combined size of all databas ...

An Axios error message indicates ERR_NETWORK and ERR_EMPTY_RESPONSE

When I initiate a Patch Request from the frontend, it takes approximately 30-40 seconds for the backend to resolve. const handleSendClick = (data: any) => { const requiredLanguages = Array.isArray(data.required_languages) ? data.required_langu ...

Implementing Immer in Typescript

Recently, I've been exploring the possibility of integrating Immer into my React project that already utilizes Typescript. Unfortunately, I haven't been able to discover a clear guide on how to effectively employ Immer in conjunction with Typescr ...

Developing a TypeScript NodeJS module

I've been working on creating a Node module using TypeScript, and here is my progress so far: MysqlMapper.ts export class MysqlMapper{ private _config: Mysql.IConnectionConfig; private openConnection(): Mysql.IConnection{ ... } ...

The partial template is not functioning as anticipated

Introducing an interface designed to accept two templates, with the resulting function being a partial of one of them (similar to React-Redux): export type IState<TState, TOwnProps> = { connect: (mapStateToProps: MapStateToProps<TState, Parti ...

Struggling to properly import the debounce function in ReactJS when using TypeScript

I am facing an issue while trying to properly import the debounce library into my react + typescript project. Here are the steps I have taken: npm install debounce --save typings install dt~debounce --save --global In my file, I import debounce as: impo ...

Revolutionizing SEO with MEAN.js dynamic metadata

After using the command yo meanjs:crud-module modulename to generate a meanjs crud module, I am facing a challenge with changing the meta data values for view.modulename.client.html. These values are generated on the server side in layout.server.view.html ...

Cluster multiple data types separately using the Google Maps JavaScript API v3

I am looking to implement MarkerClusterer with multiple markers of various types and cluster them separately based on their type. Specifically, I want to cluster markers of type X only with other markers of type X, and markers of type Y with other markers ...

Changing an Angular template.html into a PDF document within an Angular 2 application can be achieved by utilizing

Exploring Angular 2 and looking for a way to export my HTML component in Angular 2 to PDF using jspdf. I want to convert dynamically generated tabular HTML into a PDF using jspdf. Below is a snippet of sample code along with a Plunker link: import {Comp ...

The error code TS2345 indicates that the argument '{ read: typeof ElementRef; }' cannot be assigned to the parameter '{ read?: any; static: boolean; }'

Currently in the process of updating my Angular application from version 7 to version 8. Upon running ng serve, I encounter the following error: Error TS2739: Type '{}' is missing the following properties from type 'EmployeeModel': stat ...

Using Typescript to Declare Function and React Component Types

Currently challenging myself to delve into Typescript (ugh). Usually, I can deduce the appropriate type by analyzing the return values. Nonetheless, in this particular scenario, that method is proving ineffective. type SomeReactAProps = { Type1: ReactEle ...

Make sure to send individual requests in Angular instead of sending them all at once

I am looking to adjust this function so that it sends these two file ids in separate requests: return this.upload(myForm).pipe( take(1), switchMap(res => { body.user.profilePic = res.data.profilePic; body.user.coverPic = res.data.coverPic; ...

Is it time to refresh the package-lock.json file?

I'm currently in the process of updating a React app from Node 14 to 16. One step I took during the upgrade was deleting the node_modules folder and package lock, then generating a new package-lock.json file. However, this resulted in numerous compila ...

Retrieve a Targeted Value Across Numerous Arrays Using an Aggregation Filter

Here is the JSON response structure I am working with: { "_id": "5947e320d0f00f1794c87772", "selected_product": "5947e320d0f00f1794c87774", "sign_in_label": { "value": "Sign In", "translation": [ { " ...

What is the best way to organize an Angular library for multiple import paths similar to @angular/material, and what advantages does this approach offer?

When importing different modules from @angular/material, each module is imported from a unique package path, following the format of @organization/library/<module>. For example: import { MatSidenavModule } from '@angular/material/sidenav'; ...

Tips for creating a typescript module definition that exports a module dependency as one of its members

Let's consider a particular situation: I am in the process of creating typescript definitions for two commonJS modules, A and B. Module B has a dependency on module A, and to make things easier, B directly exports A as a property B.A so that users do ...

Transmitting information to the main Vue class component

I'm facing an issue with a Vue component that I've defined using Vue class components. Here is the code snippet: @Component export default class MyComponent extends Vue { value = 0; } My requirement is to create multiple instances of this comp ...