Chaining together MongoDB aggregates starting from matching documents

My goal is to filter out records that have already been matched in a previous MongoDB aggregation.

In the first match, I want to retrieve records from two countries: United States and Germany.

In the second match, I want to exclude records from a specific country, such as United States, where the level is "Beginner", while still keeping other records from United States and Germany. How can this be achieved? Example Data:

[
  {
    country: 'United States',
    personName: 'John',
    level: 'Average',
  },
  {
    country: 'United States',
    personName: 'Rina',
    level: 'Beginner',
  },
  {
    country: 'Germany',
    personName: 'John',
    level: 'Average',
  }
]

First match (correct):

{
  country: {$in: ['United States', 'Germany']}
}

Second match (incorrect):

{
  $and: [
    { level: { $ne: 'Beginner'} },
    { country: { $eq: 'United States' } },
  ]
}

I do not want to re-add the countries array in the second match phase.

Answer №1

To filter out all records that are not from 'United States', you need to use the $or operator:

db.stuff.aggregate([
  { $match: {
      country: {$in: ['United States', 'Germany'] }
    }
  },
  { $match: {
      $or: [
        { country: { $ne: 'United States' } },
        { country: { $eq: 'United States' }, level: { $ne: 'Beginner'} }
      ]
    }
  }
]);

You can simplify by combining the two match stages into one.

db.stuff.aggregate([
  { $match: {
      country: {$in: ['United States', 'Germany'] },
      $or: [
        { country: { $ne: 'United States' } },
        { country: { $eq: 'United States' }, level: { $ne: 'Beginner'} }
      ]
    }
  }
]);

Running the above queries will result in:

{
        "_id" : ObjectId("5e999bdee125b211df7f361a"),
        "country" : "United States",
        "personName" : "John",
        "level" : "Average"
}
{
        "_id" : ObjectId("5e999bdee125b211df7f361c"),
        "country" : "Germany",
        "personName" : "John",
        "level" : "Average"
}

https://mongoplayground.net/p/oXBqAzBHzUr

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

how to change class on vue function result

I need a way to display the content stored in requestData as li elements. Each list item should have an onclick function that, when clicked (selected), adds a specific value from a reference to an array. If clicked again (unselected), it should remove the ...

Axios encountering failure in Oauth 2.0 request

While I successfully managed to interact with the Yahoo Fantasy API using Oauth 2.0 in PHP, I encountered an issue when attempting to translate my code to JavaScript using the Axios HTTP request library. Unfortunately, I am getting no response. What could ...

Eliminate duplicated partial objects within a nested array of objects in TypeScript/JavaScript

I'm dealing with a nested array of objects structured like this: const nestedArray = [ [{ id: 1 }, { id: 2 }, { id: 3 }], [{ id: 1 }, { id: 2 }], [{ id: 4 }, { id: 5 }, { id: 6 }], ] In the case where objects with id 1 and 2 are already grou ...

Tips for hiding a div element until its visibility is toggled:- Set the display property of

Looking for some guidance on this jQuery code I'm working with to create a toggle menu. The goal is to have the menu hidden when the page loads, and then revealed when a button is clicked. However, currently the menu starts off being visible instead o ...

Building Firestore subcollections with the latest WebSDK 9: A step-by-step guide

I'm looking to create a subcollection within my document using the webSDK 9, specifically the tree-shakable SDK. While I have come across some solutions, they all seem to be outdated and reliant on the old sdk. Just for context, I am working with Ne ...

Experiencing difficulty with rendering a Chartist graph in an HTML page when a button is clicked

I encountered an issue while attempting to display the Chartist graph when the user clicks the button. Normally, the graph displays properly but when I try using ajax show(), the graph shrinks as shown in the image below: Without button clicked https://i. ...

Automatically refresh the D3 Sunburst visualization when the source json is modified (items added or removed)

I'm a beginner in D3 and I'm attempting to update the chart dynamically if the source JSON is modified. However, I'm facing difficulties in achieving this. Feel free to check out this plunkr Js: var width = 500, height = 500, radi ...

SQL Query for searching records by name containing multiple words in a combination

When I perform a search using the following code snippet: ....LIKE '%" + txtName.Text + "%' It retrieves all the rows that contain txtName. This method works well for names like Bijay Bijay Kumar And rows with data like Bijay, ...

An issue with MongoDB.Web has occurred: MongoDB.Driver.SafeModeResult MongoDB.Driver.MongoCollection.Insert(!!0) has encountered an error

Encountering an issue with the MongoDB.Web membership provider: An error is appearing: 'Method not found: 'MongoDB.Driver.SafeModeResult MongoDB.Driver.MongoCollection.Insert(!!0)'. My implementation is very basic, including: Using Visua ...

Is it possible to merge several blobs into one zip file using JSzip?

When attempting to download multiple images as a single ZIP file, the result is receiving separate zip files instead. The console log shows that the 'urls[]' array contains different arrays. const fileURLs = window.URL.createObjectURL(result);// ...

Update an existing JSON document

Looking for a solution to update the json file while retaining specific strings and values? const fs = require('fs'); var logPath = 'log.json' var logRead = fs.readFileSync(logPath) var logFile = JSON.parse(logRead) LogChannel = &apo ...

How can I use Google Apps Script to convert the month name in a cell formatted as "MMMM" to uppercase in Google Sheets?

I have a cell that displays the month name in date format using MMMM. How can I script to convert the month name to uppercase while keeping the cell formatted as a date? I've attempted to use toUpperCase() without success. The code snippet I'm e ...

Steps to trigger a JavaScript popup from an iframe window to the parent window

Currently I am developing a web application using JSP with JavaScript. Within the parent window, an iframe is being utilized. The issue arises when a button in the iframe page is clicked, as it opens a popup window within the iframe itself. However, my obj ...

What is the process for setting a cookie in Next.js from a different backend server?

I have encountered an issue with my Node.js API built using Express.js. The cookie I set works perfectly fine on Postman, but for some reason, it is not functioning properly in Next.js. I set the cookie when a user logs in, but it is not appearing in the b ...

Tips for transferring values from two separate select tags for processing via Ajax and jQuery

HTML Code: <select id="sel"> <option value="dog">dog</option> <option value="cat">cat</option> </select> <select id="sel2"> <option value="chocolate">chocolate</option> <option valu ...

Utilizing the power of jQuery's $.each method to dynamically generate HTML select options within an AJAX

I am working with a bootstrap modal that includes a form which requires data from the database. To retrieve this data, I am using PHP as shown below: public function get_view_for_inspection_report_belum_eor(){ $q = $this->inspection->get_view_fo ...

Retrieve data from each URL listed in a JSON array using React

My json file structure was as follows: [ { "name": "google", "route": "/google", "url": "www.google.com" }, { "name": "bing", "route": " ...

Guide on how to bypass IDM when downloading a PDF file through a GET request

When I try to fetch a PDF by sending a GET request to the server and open it in a new tab, IDM interrupts my request and downloads the file instead. It changes the server response status to 204 and removes the headers. How can I prevent IDM from doing th ...

The notification bar only makes an appearance when necessary

I am currently working on a dynamic piece of code that sends a request to PHP and receives a response. The goal is for the notification bar to fadeIn() and fadeOut() every time there is a new notification. However, I have encountered an issue where the n ...

Tips for showing validation message just one time along with multiple error messages

Exploring ways to implement a dynamic form submit function using jQuery. $('#btnsumbit').click(function() { $('.required_field').each(function() { if ($(this).val() == "") { alert('please fill field'); ret ...