Query a MongoDB collection by applying filters using data from a separate collection

Being new to MongoDB, I have created the following schemas:

const postSchema = new mongoose.Schema(
    {
        content: { type: String, required: true, index: "text" },
        author: { type: ObjectId, ref: "User", required: true, index: true }
    }
);
const muteWordSchema = new mongoose.Schema({
    word: { type: String, trim: true, required: true },
    match: { type: String, enum: ["exact", "contains", "startsWith", "endsWith"], required: true },
});

My goal is to:

  1. Retrieve all posts
  2. Retrieve all muted words
  3. Convert the muted words into corresponding regular expressions. For example,
    { word: "test", match: "startsWith" }
    will be transformed into /(^|\s)test/g, and so on.
  4. Filter out posts that match these transformed regular expressions.

How can I accomplish this task using aggregation pipelines?

Answer №1

I didn't receive a response, but I will still share the solution I discovered so it can benefit others facing a similar issue.

db.posts.aggregate([
    {
        $lookup: {
            from: "mutedwords",
            pipeline: [
                {
                    $project: {
                        _id: 0,
                        regEx: {
                            $switch: {
                                branches: [
                                    {
                                        case: {
                                            $eq: [ "$match", "startsWith" ]
                                        },
                                        then: {
                                            $concat: [
                                                "\\W+",
                                                "$word",
                                                ".*"
                                            ]
                                        }
                                    },
                                    {
                                        case: {
                                            $eq: [ "$match", "endsWith" ]
                                        },
                                        then: {
                                            $concat: [
                                                "\w*",
                                                "$word",
                                                "(\\W+|$)"
                                            ]
                                        }
                                    },
                                    {
                                        case: {
                                            $eq: [ "$match", "exact" ]
                                        },
                                        then: {
                                            $concat: [
                                                "\\W+",
                                                "$word",
                                                "(\\W+|$)"
                                            ]
                                        }
                                    }
                                ],
                                default: "$word"
                            }
                        }
                    }
                },
                {
                    $group: {
                        _id: undefined,
                        result: {
                            $addToSet: "$regEx"
                        }
                    }
                }
            ],
            as: "mutedWords"
        }
    },
    {
        $addFields: {
            mutedWords: {
                $arrayElemAt: ["$mutedWords.result", 0]
            }
        }
    },
    {
        $match: {
            $expr: {
                $eq: [
                    {
                        $filter: {
                            input: "$mutedWords",
                            cond: {
                                $regexMatch: {
                                    input: "$content",
                                    regex: "$$this",
                                    options: "i"
                                }
                            }
                        }
                    },
                    []
                ]
            }
        }
    },
    {
        $unset: "mutedWords"
    }
]);

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

Uncertainty regarding API endpoints in a React project

I am currently in the process of building a comprehensive MERN app that allows users to submit reviews. However, I have encountered some confusion regarding routing and API endpoints. Specifically, when attempting to view my AddReview component in the brow ...

Ajax call fails to trigger upon change

Currently, I am focusing on creating an HTML table with a form that contains a select element offering options for ALL and Biscuits. Initially, the table populates correctly upon loading. However, I am facing an issue when attempting to trigger an AJAX ca ...

Is there a way to dynamically add or modify a JavaScript timestamp component after the webpage has finished loading?

Context: Utilizing the SailsJS framework to showcase the timestamp of data model updates. The framework, originating from 'parasails', leverages Vue.js and offers the <js-timestamp :at="1573487792252"> component to display elapsed time like ...

The 'save' property is not found on the 'IProtein' type. Error code: 2339

Encountering an issue with the mongoose "save" function where the error message reads as "Property 'save' does not exist on type 'IProtein'.ts(2339)". I have come across a solution involving the addition of "extends mongoose.Document" ...

Is it advisable to utilize $locationProvider in AngularJS version 1.3.14?

Attempting to utilize html5Mode to remove # from the url in SPAs resulted in an error when using $locationProvider in AngularJS v 1.3.14. The reason for this error is unclear. The code snippet and console error are provided below for reference. Front End: ...

Update the link by simply clicking on a div tag

I am currently working on a PHP page and my goal is to add the extension ?id=variable_value to its URL when I click on a specific div. However, whenever I try to do this, it shows me an error message stating that the URL with the extension is undefined. B ...

Error in Bootstrap Auto-complete: Property " " cannot be read because it is undefined

I am attempting to implement Bootstrap autocomplete with Django. I have tested the calls and the ajax request successfully sends to my views, but I am not receiving a response in my form. An error appears in the console stating: Uncaught TypeError: Cannot ...

Retrieve all articles in groups of 10, ensuring that each article includes the necessary details of relevant users

In my project, I have set up two models named user and article. The data structure for each model is outlined below: const userSchema = Schema({ name: String, email: String, password: String }); const User = mongoose.model(‘user’, userSchema); mo ...

eliminate the common elements between two arrays in typescript/javascript

I have two lists of objects, each containing two fields: let users1 = [{ name: 'barney', uuid: 'uuid3'}, { name: 'barney', uuid: 'uuid1'}, { name: 'barney', uuid: 'uuid2 ...

Easily transform your Twitter Bootstrap menu dropdown to appear on hover instead of click with this simple solution

Is there a way to make the toggle dropdown button display the dropdown menu when hovering over it instead of clicking? I tried using the Bootstrap method $().dropdown('show'). What are your thoughts on this approach? $(document).on("mouseenter ...

What is preventing me from being able to effectively transmit the array using the POST method in Express?

As a newcomer trying to learn Express, I believe I am on the right path, but I am currently facing some challenges with the POST method. The issue I'm encountering is as follows: Whenever I send a POST request to an HTTP file, I receive an empty ob ...

Using wildcard in Angular app for MQTT observation

My curiosity lies in MQTT wildcards and how they function, specifically while utilizing the mosqitto broker. Let's say I have around 1-2k topics. In my frontend, I am observing them with a single-level wildcard using ngx-mqtt. Will there be a separat ...

Tips for sending a string from the state of a React component to an external Python script

My journey into ReactJS and web development is just beginning. I am currently working on a web application where users can input mathematical expressions as strings. Upon submitting the input, I intend to process it using a Python script and display the o ...

Why is the jQuery ajax file uploading feature failing to function properly in the IE9 standard mode?

My file upload function works well in browsers like Chrome and IE10, but encountered an issue when tested on IE9. The Action controller reported that Request.Files were returning files with '0' length. I'm unsure if this problem is related ...

The color of my Navbar remains stationary despite implementing Javascript for scroll effects

I am having trouble with the Javascript portion of my code, which I copied from a tutorial. The Navbar is not changing color when scrolled, and I'm not sure if the issue lies with the Javascript, the CSS, or if I need to add 'scrolled' to th ...

JavaScript facing issue with $.get command executing in incorrect order

I have encountered an issue with my JavaScript code where it is not running in sequence. The script includes an unload function that uses the $.get jQuery command to fetch a file, which is then supposed to be printed to an external device. To debug this ...

The speed of Mongodb aggregation is negatively impacted if the number of search records falls below the specified limit

I have been using a MongoDB aggregation query to extract data from a table that involves multiple lookup stages to join various tables. However, I encountered an issue when the number of records in the search result is less than the specified limit in the ...

How do I execute raw queries with Yii's ActiveRecord when using MongoDB?

Being a newbie in both MongoDB and Yii framework, I am in need of selecting data from a collection of documents with a complex structure (nested arrays of data). I have successfully written a query to accomplish this, but now I am unsure of how to integrat ...

I'm interested in learning the best way to insert the images from this JSON file into the corresponding div elements

I have completed developing a clone of an Instagram web page. Although I can retrieve data from the JSON file and insert it into the <img> tag, I am facing difficulty in displaying each image above its respective .below-image div with consistent spac ...

Unable to properly display the message in Angular

<!DOCTYPE html> <html ng-app> <head> <script data-require="angular.js@*" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script> <link rel="stylesheet" href="style.css" /> ...