Ways to verify if two items within a collection of objects share a common value in MongoDB

I have a collection of data called users stored in mongoDB that has the following structure:

_id: ObjectId,
sports: [
  {
    name: 'cricket',
    history: [
      {
        from: 10,
        to: 30
      },
      {
        from: 30,
        to: 30
      }
    ]
  },
  // ... other sports as well
]

My goal is to query for users who have at least one element inside sports.history where the condition from === to is true. Each user can have multiple sports, each with its own history data.

I'm looking to achieve this filtering directly within the query, rather than fetching users and then applying the filter in my express app afterwards.

Any assistance on how to accomplish this would be greatly appreciated. Thank you!

Answer №1

Utilizing the $expr operator, you can effectively query the collection by flattening the 2D array '$sports.history' and filtering it based on certain conditions using array operators. Start by flattening the array with $reduce:

 {
    $reduce: {
        input: "$sports.history",
        initialValue: [],
        in: { $concatArrays: [ "$$value", "$$this" ] }
    }
}

Then, apply a filter to the reduced array using $filter

{ $filter: {
    input: {
        $reduce: {
            input: "$sports.history",
            initialValue: [],
            in: { $concatArrays: [ "$$value", "$$this" ]
            }
        }
    },
    cond: {
        $eq: ['$$this.from', '$$this.to']
    }
} }

Determine the length of the resulting array using $size:

{ $size: { 
    { $filter: {
        input: {
            $reduce: {
                input: '$sports.history',
                initialValue: [],
                in: { $concatArrays: [ '$$value', '$$this' ] }
            }
        },
        cond: {
            $eq: ['$$this.from', '$$this.to']
        }
    } }
} }

If the length of the filtered array is greater than zero, then the user exists:

{ $gt: [
    { $size: { 
        $filter: {
            input: {
                $reduce: {
                    input: "$sports.history",
                    initialValue: [],
                    in: { $concatArrays: [ "$$value", "$$this" ] }
                }
            },
            cond: {
                $eq: ['$$this.from', '$$this.to']
            }
        }
    } },
    0
] }

In conclusion, your final query should resemble this:

db.users.find({
    $expr: {
        $gt: [
            { $size: {
                $filter: {
                    input: {
                        $reduce: {
                            input: "$sports.history",
                            initialValue: [],
                            in: { $concatArrays: [ "$$value", "$$this" ] }
                        }
                    },
                    cond: {
                        $eq: ['$$this.from', '$$this.to']
                    }
                }
            } },
            0
        ]
    }
})

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

Utilizing the power of Material-UI with React in conjunction with Python-Django: A comprehensive

I am seeking guidance on implementing React with Material UI components in my web application. The technologies I have utilized in multiple projects include: Materialize CSS, Javascript, Jquery. The technologies I wish to explore for future projects are ...

What are the steps for creating a new npm package based on an existing one?

I'm a newcomer to the node ecosystem and the npm package system. In my redux/react web app, I currently make use of the photoswipe package alongside react-photoswipe. Recently, I decided to extend the functionality of the photoswipe package by making ...

Search for elements within the database by using the recursive feature of M

I am working on a search query to retrieve 'n' number of videos from a collection. The user has primary, secondary, and tertiary language preferences (Tamil(P), Hindi(S), English(T)). My goal is to first search for videos in the primary language, ...

Issue "RangeError: minimumFractionDigits value is invalid" when using ChartJS in a Next.js application

I'm currently working on developing an application utilizing react-chartjs-2.js. The functionality is smooth in my local environment, but when moved to production, I encounter the following error: Application error: a client-side exception has occurre ...

Adjusting the zoom level in leaflet.js ImageOverlay will cause the marker

Using ImageOverlay to display an image as a map with Leaflet.js, but encountering issues with marker positions shifting when changing the zoom level. Followed instructions from this tutorial, and you can find a code pen example here. // Code for markers ...

The React DOM element undergoes mounting and unmounting on each render cycle when it should be simply altered/updated

As per the React documentation, callback refs are invoked during both component mounting (with the DOM element's value) and unmounting (with null): When a React component mounts, the ref callback is triggered with the actual DOM element, and when it ...

I am having trouble getting ng-change to work. Can someone explain how to properly implement ng

I am facing an issue where the ng-change function is not working for obtaining the team_id and team name. Can someone suggest a more efficient solution to resolve this problem? <th style="width:20%"> <select style="height: 40px; fon ...

Is there a way to automatically close all open sub-menus when clicking on a different parent menu item?

Check out this LINK for the code I am using. When I click on the Parent Menu, such as Services, the sub-menu of the Services menu will open. However, when I click on another menu, the sub-menu will also open. I want the previous sub-menu to close when I c ...

Page redirects automatically after AJAX call

I'm a beginner when it comes to using AJAX and I am trying to delete a student from a list through an AJAX request. I want the response of the request to be displayed on the same page within a specific div, but instead, the response keeps redirecting ...

Node.js: Issue with static file caching caused by superfluous query parameter

My Node.js code for caching static files looks like this: app.use(express.static(path.join(__dirname, "public"), { maxAge: (process.env.NODE_ENV === "local") ? 0 : 31557600000 })); The public folder contains all the necessary static files for my ser ...

Passing the $scope variable between functions

Here is the function in my angular controller: $scope.selectinteresteduser = function(Id){ $scope.selecteduserid = Id; } $scope.sendMessageToEmployeer = function($scope.selecteduserid) { alert($scope.selecteduserid); } I am looking for a way to pa ...

Utilizing socket.io to deliver messages loaded directly from the database

I have been working on a project involving node, express, mongo, and socket.io. I have successfully established a socket connection and saved messages to the database. My current goal is to display all previous messages to new users joining a discussion. H ...

Troubleshooting guide: Fixing issues with external HTTP requests in a Node.js application

When attempting to integrate an external HTTP request into a Node.js/Express application, I encountered an 'ECONNREFUSED 127.0.0.1:80' error. This issue persists whether it's a POST request or a simple GET request like querying Google. My se ...

Initiate the countdown when the button is pushed

Recently ran into an issue where a button triggers a command to a Perl script, causing the page to continuously load for 60 seconds. To provide users with transparency on when the Perl script will be finished running, I implemented a JavaScript countdown t ...

Moving object sideways in 100px intervals

I'm struggling to solve this issue. Currently, I have multiple div elements (each containing some content) that I need to drag and drop horizontally. However, I specifically want them to move in increments of 100px (meaning the left position should b ...

Instructions for adding a name to a string based on certain conditions

I am attempting to prepend a company name to a card number using the code provided. The challenge I am facing is incorporating the specific rules for each company as conditions for an if statement. Although I acknowledge that my current approach with the ...

Dynamically loading a webpage with an element roster

I have a list and I want it so that when a user clicks on the sport1 list item, results from the database table sport1 will be displayed. Similarly, if they click on the education1 list item, results from the education1 table should be shown. The issue i ...

Avoid the ability for individuals to interact with the icon embedded within a button

I'm currently working on a website where users need to interact with a button to delete an "Infraction." The button has a basic bootstrap style and includes an icon for the delete action. <button referencedInfraction="<%= i.infractionID %>" ...

Uploading images to a webpage using Node.js

How can I display images from a nodejs express server on my website when the file path includes subfolders? I have tried using a relative path to the file, but it's not working as expected. <img src="pictures/?path=rel_path"/> When attempting ...

Looking for a particular root node in a tree structure?

I am currently working on converting docx files to xml and using DOM to locate the parent node of a specific element. For instance <chapter> <title> <label>Chapter 1 </label> </title> ...