Tips for converting the logical statement "NOT (A AND B)" into a mongodb query

In my Node.js web application, I have created a grammar using peg.js for simple search queries. The challenge I am facing is translating the Abstract Syntax Tree (AST) it generates into a $match parameter for MongoDB's aggregate function. Most scenarios work well, but I'm struggling with how to represent NOT (A AND B) in MongoDB.

Here are some sample data:

{ _id:123, labels:['a', 'b', 'c'], tags:['g', 'h', 'i']},
{ _id:456, labels:['a', 'e', 'f'], tags:['i', 'j', 'k']},
{ _id:789, labels:['c', 'd', 'b'], tags:['h', 'l', 'm']}

A user may input queries like NOT (labels:a AND labels:b) or NOT (labels:b AND tags:h), both of which are valid based on my grammar.

The first query aims to retrieve documents that do not contain both 'a' and 'b' in their labels field (so only the second and third document would be returned). For the second query, it should find all documents without 'b' in the labels field and 'h' in the tags field.

I've found that MongoDB's $not operator doesn't provide a straight-forward way to negate logical operations as needed. Ideally, I'd like to achieve something like this:

{
    $not: {
        $and: [
            { labels: a},
            { labels: b},
        ]
    }
}

or

{
    $not: {
        $and: [
            { labels: b},
            { tags: h},
        ]
    }
}

If there is another operator that can help accomplish this, please let me know. Ultimately, I'm looking for a solution that allows building complex compound queries inside parentheses and easily negating them if there's a NOT.

EDIT: Added more data to the dataset and further clarified my specific requirements for a solution.

Answer №1

To achieve the desired result for one field in the original question, you can use the following code snippet:

{
    'labels': {
        '$not': {
            '$all': [
                'a',
                'b',
            ]
        }
    }
}

For multiple fields, you will have to separate them but the following query will work effectively:

{
    '$and': [
        {
            'labels': {
                '$not': {
                    '$all': ['b'],
                },
            },
        },
        {
            'tags': {
                '$not': {
                    '$all': ['h'],
                }
            }
        }
    ]
}

It is not possible to have 'not' as the main root element.

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

Trouble accessing JSON file on FileZilla/FTP server

When I transfer my project to the FTP server, the JSON file I am using for data is not functioning properly. However, when I run the program on XAMP, my local server, it works perfectly. Upon inspecting the element on the FTP server, I noticed that the JSO ...

Tracking the click location inside a div element

Is there a way to accurately determine the position of a click inside a div? I need the mouse cursor to be exactly where the initial click occurred relative to the moving window as the mouse drag moves it. Below is the structure of the window: <div id ...

Converting CoreMongooseArray into Regular Array

Currently, I am selecting two elements from one schema and trying to update them in another schema. To achieve this, I have used the slice method to extract the first two elements from an array. However, I am encountering an issue where the output shows as ...

Changing elements within Angular Scope while in ng-repeat loop

Creating an HTML form using ng-repeat to generate form elements from an object in the scope is a common practice. However, issues may arise when trying to update values outside of the ng-repeat block. Here's a basic example: <div ng-app="App"> ...

Streamlining async/await in for loops using Promise.all: A guide

I'm trying to understand how Promise.all() works in this code. I've learned that you can execute async operations concurrently with Promise.all() for better performance. Currently, the code uses nested for-loops (which is not ideal): type ListGro ...

What could be the reason for this JSON being considered "invalid"?

Despite passing validation on jsonlint, both Firefox and Chrome are rejecting this JSON: { "messages": [ { "subject": "One" }, { "subject": "Two" }, { "subject": "Three" ...

The Material-UI data grid can handle rendering up to 101 rows of data

I am working with a data grid that pulls data from an API response and then renders it for server-side rendering. Here's the SQL query I use to fetch data from the database: select * from orders This query retrieves all 350 rows from the 'orders ...

Exploring the potential of $scope within $timeout in AngularJS

I am attempting to display a default message on a textarea using AngularJS. Some of the values I want to include require the use of $timeout to retrieve the values. The message does not appear to show up with the following code: <textarea class="t ...

Adjusting the view to focus solely on the visible portion of the webpage

Is there a way to achieve zooming in and out on a website similar to how it works on the site ? I want only the visible area to zoom in or out when users interact with their browser. I searched online for a solution but couldn't find one. Any suggesti ...

Switching Div Elements Created by PHP

Utilizing MySQL, I am fetching data to dynamically generate nested div tags in a hierarchical structure. This structure consists of div tags within div tags within div tags, all uniquely identified through PHP-generated ids: <div class="holder"> ...

What is the best way to update a div element without the need for double clicking?

Let me explain this clearly. Currently, I have a table displaying in HTML when called. However, I want the table to disappear and show filtered results when someone enters a president's name and clicks on "Search for Presidents". I attempted using a c ...

Why does an array return [object Object] upon any interaction, especially when it was returned from a class?

Introduction to SPA and Router I am currently delving into the workings of single page applications, specifically focusing on routers, state management, routes, and more. I have successfully implemented a basic hash router that can display content on a fr ...

Exploring the possibilities of DOM events within nodeJS and express

Does anyone have experience catching a DOM event with NodeJS and Express? I've been looking into the "socket.io" module but am having trouble using it properly. My goal is to run some code whenever the content of a "file input" changes in the DOM. & ...

Image remains fluid within a static div without resizing

Any assistance would be greatly appreciated. I am currently facing an issue with a fixed div that is floating at the bottom of the screen, serving as ad space for the mobile version of a website. The problem arises when attempting to resize the browser win ...

Using Mongodb to Locate Information Within a Specified Date Range

I have a specific scenario where I need to extract information between two specific dates. Let's say I have the following document in my collection: { "fromDate": "2022-07-07T00:00:00.000+00:00", "toDate": "2022-12-12T11:59:59.999+00:00", ...

Unable to simulate default export in the tested document

I am currently working on a Typescript project and facing the challenge of adding tests for functions that are responsible for sorting through MongoDB responses to extract meaningful results. To facilitate this, I have set up an in-memory mock of the datab ...

Styling buttons with different colors using React onClick event.getSelectedItem() method

I am having an issue with adding a border when the class is set to "transportation active" in my React code. When I click on one of the icons, all of them become active instead of just the clicked one. This behavior is not what I want, as I only want the ...

Attaching the JSON data to ngModel in Angular 2

I have received a json response containing various fields, including the rewards.rewardName value. I'm trying to figure out how to bind this specific value to [(ngModel)] in Angular 2. [ { "id": 18, "gname": "learning ramayanam", "goalCat ...

The Fort Awesome icon appears larger than the browser anticipated

Utilizing Fort Awesome Icons. While displaying one of my icons, it appears that the browser expects the height to be 90px, but the icon is taller than that, resulting in overlapping other content on my page. <script src="https://use.fortawesome.com/66 ...

Error message saying "AuglarFire Authentication failing due to unrecognized provider with routers"

Recently, I've been exploring the Firebase documentation on authentication with Routers. In my project, I'm using Ionic with ui-router, incorporating abstract views and actual views with controllers. Here's the structure I have set up: .sta ...