What is the process for conducting a comprehensive match search using dual parameters?

I am working with a database model

Schema({
  members: [
    {
      type: String,
      required: true,
      ref: "User"
    }
  ],
  createdAt: {
    type: Date,
    default: Date.now(),
    required: true
  },
  lastMessage: {
    message: {
      type: String,
      required: true
    },
    from: {
      type: String,
      required: true
    },
    createdAt: {
      type: Date,
      required: true
    }
  },
  messages: [
    {
      createdAt: {
        type: Date,
        required: true
      },
      message: {
        type: String,
        required: true
      },
      from: {
        type: String,
        ref: "User",
        required: true
      }
    }
  ]
});

The above code is used to query for specific documents

Chats.countDocuments(
      {
        members: {
          $in: ["userIdOne", "userIdTwo"]
        }
      },
      cb
    )

In the code snippet, I am using $in operator to filter data, but it retrieves all documents containing either one of the specified userId.... I actually need to retrieve only one document that contains both user ids.

Is there a way to achieve this?

Answer №1

Consider utilizing the $all operator in this scenario

Chats.countDocuments(
  {
    members: {
      $all: ["userIdOne", "userIdTwo"]
    }
  },
  callbackFunction
)

Answer №2

To achieve an exact match, you can utilize the $setEquals aggregation operator.

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $eq: [
          {
            $setEquals: [
              "$members",
              [
                "userIdOne",
                "userIdTwo"
              ]
            ]
          },
          true
        ]
      }
    }
  },
  {
    $count: "count"
  }
])

Input Data:

[
  {
    "members": [
      "userIdOne"
    ]
  },
  {
    "members": [
      "userIdTwo"
    ]
  },
  {
    "members": [
      "userIdOne",
      "userIdTwo"
    ]
  },
  {
    "members": [
      "userIdOne",
      "userIdTwo",
      "userIdThere"
    ]
  }
]

Output Result:

[
  {
    "count": 1
  }
]

Check out the Playground

You can incorporate this with Mongoose as shown below:

  const result = await Chats.aggregate([
    {
      $match: {
        $expr: {
          $eq: [
            {
              $setEquals: ["$members", ["userIdOne", "userIdTwo"]]
            },
            true
          ]
        }
      }
    },
    {
      $count: "count"
    }
  ]);

  const count = result[0].count;

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

Tips for customizing the selection tip of a custom cursor using CSS

I have integrated a color picker jquery plugin on my website to allow users to pick colors from an image. I made a modification in the CSS to change the cursor to an eyedropper icon. However, currently when clicking on the image, the color pointed by the u ...

Node.js data querying methods and best practices for code structuring

Recently delved into the world of nodejs and still fairly new to JavaScript. In my quest for best practices, I stumbled upon this helpful resource: Currently, I am working on an application following the structure recommended in the resource. The suggesti ...

A guide to implementing drag and drop functionality using JavaScript

I have developed a unique drag and drop application that features both a left and right panel. The issue I am facing is that when I drag the ball from the left panel to the right panel, it does get dragged successfully. However, the problem arises when the ...

A single pledge fulfilled in two distinct ways

My code ended up with a promise that raised some questions. Is it acceptable to resolve one condition with the token string value (resolve(token)), while resolving another condition with a promise of type Promise<string>: resolve(resultPromise); con ...

Node-archiver: A tool for dynamically compressing PDF files

I am currently working on a project that involves generating multiple PDF files using pdfkit. I have an array of users, and for each user, I create a report using the createTable() function. The function returns a Buffer, which is then passed to archiver t ...

Combining multiple arrays in Node.js to create a single JSON file

I'm exploring the world of nodejs and currently working on creating a Json parser that will pull data from a Json API, allow me to access specific data points (some of which will need transforming), and then save it to a Json file. I recently came ac ...

Is there a way to prevent the entire row from being selected when a radio button is clicked in an md-data

Can anyone assist me with an issue I am having with my data table? When I select a radio button, the entire table row is getting selected instead of just the radio button. Below is the code snippet: https://i.sstatic.net/dicwF.png My Expectation: When c ...

Learning to control the JavaScript countdown clock pause and play functionality

How can I control the countdown timer to play and pause, allowing me to resume at the exact time it was paused? At the start, the timer is set to play. Please keep in mind that the button appears empty because the font-awesome package was not imported, b ...

Verify whether the keys of Object1 exist in Object2; if they do, compare their corresponding values

How can I accomplish the following task? I want to check if the keys of object1 are present in object2. If a key is found, I need to compare its value with that of object2. If the values are different, I should replace the value in object2 with the one fro ...

Is there a way to customize the progress bar percentage in Ant design?

I am currently utilizing React JS and importing the Ant Design progress component (refer to https://ant.design/components/progress/). However, I am facing difficulties in dynamically editing the percentage of the progress bar using JavaScript after it has ...

Determining the size of an element in AngularJS without relying on a function

Here is the HTML content I am working with: <span>{{queries['q1_name'].parameters.length}}</span> <!--Not working: Doesn't show length of parameters--> Below is my JavaScript object: $scope.queries = {"q1_name": ...

Tips for cropping an image using CSS with dimensions specified for width, height, and x and y coordinates

As I work on implementing a cropping feature using react-easy-crop, my goal is to store the user's image along with pixel coordinates that dictate their preferred cropping area. My objective is to utilize the parameters provided by react-easy-crop in ...

Issues with the update of class properties in Node.js using Express

I am facing some challenges with a .js Object's attribute that is not updating as expected. Being new to the world of JavaScript, I hope my problem won't be too difficult to solve. To begin with, here is a snippet from my Node class: Node = fu ...

Ensure that all asynchronous code within the class constructor finishes executing before any class methods are invoked

Looking to create a class that takes a filename as a parameter in the constructor, loads the file using XmlHttpRequest, and stores the result in a class variable. The problem arises with the asynchronous nature of request.onreadystatechange, causing the ge ...

Difficulty altering link hover background color

I'm having trouble changing the hover effect background-color on the tweets of this page: Despite my efforts, all the links except for the latest tweets are working perfectly. What am I missing? Here's what I've been trying... <script& ...

Mastering the Art of Utilizing $(this) in jQuery

$(".item_listing").hover(function(){ $(".overlay_items").display(); },function(){ $(".overlay_items").hide(); } ); This is my jQuery code. I am trying to display the "overlay_items" div when the "item_listing" div is hovered ov ...

Enhancing time slot height on Fullcalendar V5: A step-by-step guide

Curious about adjusting the height of time slots in Fullcalendar V5 - any tips? ...

Wait to display the page until all AngularJS directives have finished loading their HTML content

I've encountered an issue in my AngularJS application where I created directives that load external HTML templates from another URL. The problem is that when I navigate to the page, the binding works fine but the directive's HTML doesn't loa ...

A guide on using Sinon to mock a custom $http transform

Exploring the proper method for mocking an http post with a custom transform in Angular using the Sinon mocking framework. In my CoffeeScript Sinon unit test setup, I define mocks like this: beforeEach module(($provide) -> mockHttp = {} $provide.value ...

Ways to avoid browser refresh when uploading files in React applications

I'm working with a simple file upload form in React using hooks. import React, { useState } from 'react'; import { FlexContainer } from '@styles/FlexContainer'; const TestUpload = () => { const [file, setFile] = useState<F ...