The process of retrieving matching strings from two collections in MongoDB

There are two collections: Collection A consists of:

-> {"_id": .... , "data":"demon"}
-> {"_id": .... , "data":"god"}

and Collection B consists of:

-> {"_id": .... , "title": "Book A", "description": "this book is about a demon."}
-> {"_id": .... , "title": "Book B", "description": "this book is about a god from Greek."}
-> {"_id": .... , "title": "Book C", "description": "this book is about a dog."}

The task at hand is to retrieve documents from Collection B where the description does not contain any text present in the "data" field of Collection A.

To achieve this in Mongo Query using Plain JS:

collectionA.filter( x => { return !collectionB.some(y => x.description.includes(y.data)});

So the question remains, how can this be accomplished in MongoDB?

Answer №1

Although this code snippet seems to achieve the desired outcome, its efficiency may be questionable when dealing with large datasets.

db.A.aggregate([
    {
        $project: {
            _id: 0,
            data: 1
        }
    },
    {
        $lookup:
        {
            from: 'B',
            let: { word: '$data' },
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $regexMatch: {
                                input: '$description',
                                regex: '$$word'
                            }
                        }
                    }
                },
                {
                    $project: { _id: 1 }
                }
            ],
            as: 'found'
        }
    },
    {
        $group: {
            _id: null,
            ids: {
                $addToSet: {
                    $arrayElemAt: ['$found', 0]
                }
            }
        }
    },
    {
        $set: {
            ids: {
                $map: {
                    input: '$ids',
                    in: '$$this._id'
                }
            }
        }
    },
    {
        $lookup: {
            from: 'B',
            let: { found_ids: '$ids' },
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $not: {
                                $in: ['$_id', '$$found_ids']
                            }
                        }
                    }
                }
            ],
            as: 'docs'
        }
    },
    {
        $unwind: '$docs'
    },
    {
        $replaceWith: '$docs'
    }
])

https://mongoplayground.net/p/YMrYeiUOQdo

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

Encountering a NullPointerException when running a basic test on Mongo-Hadoop

I posted a question in the support forum on an open issue regarding my application that currently uses MongoDB as the data layer. Since I didn't receive any response, I decided to seek help here. The application is facing performance issues with Mong ...

What causes errors in URL routeProvider with AngularJS?

Implementing routeProvider in Angular JS allows me to structure my links like this: www.site.com/profile#/profile/profession/3 However, when trying to access the page, Angular JS displays the following error message: Uncaught Error: Syntax error, unreco ...

Showing the initials of a user at the top of an SVG using ReactJS

https://i.sstatic.net/oJgXs.png I require the user's initials to be displayed on the avatars as a grey circle with those initials. I have the function ready, but I am unsure of how to implement it in the JSX code for the Dropdown menu (using Semantic ...

Attempting to run the npm install command led to encountering a SyntaxError with an

Recently, I made some alterations to my npm configuration and ever since then, I have been consistently encountering the same error whenever I try to install various packages. It seems that due to a personal mistake in changing the npm settings, I am now u ...

Unable to retrieve data from mongoDB, received an HTML template instead of the expected data

When attempting to retrieve data from mongoDB's collection of products, instead of receiving the expected array or object containing the data, an HTML template is returned. What might be causing this issue? The database connection has been confirmed a ...

children blocking clicks on their parents' divs

I previously asked a question about a parent div not responding to click events because its children were blocking it. Unfortunately, I couldn't recreate the issue without sharing a lot of code, which I didn't want to do. However, since I am stil ...

Combine two events in jQuery using the AND operator

Can I create a condition where two events are bound by an AND logic operator, requiring both to be active in order for a function to be called? Let's say you have something like this: foobar.bind("foo AND bar", barfunc); function barfunc(e) { al ...

Forwarding requests via middleware in next.js 13 AppDir: true

I am currently working on implementing a redirect feature in next.js 13 when the jwt back-end is not received. This is being done with the appdir activated. This is the code in my middleware.ts file: import { NextResponse } from 'next/server' im ...

Simple method for sending a JavaScript array or its data to a servlet utilizing jQuery's ajax() functionality

Seeking advice on passing data from a Javascript array to a servlet using the ajax() method of jQuery. Is there a straightforward way to accomplish this task? The index values in the array are meaningful numbers that are not in order, which complicates th ...

The execution of the Ajax success call is failing to take place

Looking at my recent AJAX call, I realized there might be an issue with how I'm sending the parameters. $.ajax({ type: "POST", url: "Default.aspx/GeneratePdfs", data: '{frequency: "' + $('#ddlReportFrequenc ...

Is there a way to submit a form without navigating away from the current webpage?

I'm working on a registration form and I need help figuring out how to send the input information to the action.php file without the user being redirected to it. Is there a way to have the form submitted in the background and then redirect the user ba ...

Compatibility between pymongo version 4.1.1 and mongoengine

After updating to pymongo 4.1.1 and upgrading mongoengine to version 0.24.1, I encountered an error message: File "pymongo/collection.py", line 1610, in find return Cursor(self, *args, **kwargs) TypeError: __init__() got an unexpected keyword argument ...

Why is JavaScript unable to fetch JSON data from C when the uint32 value is a multiple of 256 plus 10?

After receiving some helpful feedback, I decided to make some changes to this question that I posted yesterday. The title and content have been edited for clarity based on the new information I've learned. Recently, I've been utilizing C code to ...

Is utilizing web workers for numerous simultaneous intensive computations a viable strategy?

Is it necessary to create multiple worker files for each concurrent heavy calculation with the same formula, or can I work with just one? ...

Multiplication cannot be performed on operands of type 'NoneType'

Hello everyone, I am attempting to calculate the unit price and quantity from this table using the following model: class Marketers(models.Model): category =models.ForeignKey(Category, on_delete=models.CASCADE, null=True) name =models.CharField(max ...

What is the best way to symbolize a breadcrumb offspring?

In my table representation, the breadcrumb is shown as: <ol class="breadcrumb" data-sly-use.breadcrumb="myModel.js"> <output data-sly-unwrap data-sly-list="${breadcrumb}"> <li itemscope itemtype="http://data-vocabulary.org/ ...

Have you ever wondered how the automatic video play on scroll feature works on Tiktok.com and YouTube shorts when using a mobile device?

My goal with React JS is to develop a website similar to Tiktok, where the video below will automatically play with sound as the user scrolls down. I attempted to set this up using window.addEventListener("scroll",...), but after looking into it further, ...

How can one determine if there are additional documents available for pagination within MongoDB?

Currently I am in the process of developing a Node.JS application that is connected to MongoDB. One key feature I need to incorporate is the ability to list objects efficiently. The pagination aspect has already been established using the skip() and limit( ...

Enhance information flow within pages using SWR in NextJS

Utilizing SWR in a NextJS project has been a great experience for me. I have successfully fetched a list of data on my index page and added a new entry to the data on my create page. Now, I am looking to take advantage of SWR's mutate feature to updat ...

What is the best way to store a username and password within a JavaScript object in ReactJS?

I am encountering an issue with obtaining the login credentials from the object. Although the code snippet below functions perfectly well with other forms. SignIn.js export default function SignIn(props) { const [state, setState] = useState({ userna ...