Is there a way in MongoDB to compare all elements in a collection with a larger array?

Imagine I am working with a collection that contains 3 items:

[
    {
        id: 'x',
        elements: [10, 20, 30]
    }, {
        id: 'y',
        elements: [40, 50, 60]
    }, {
        id: 'z',
        elements: [70, 80, 90]
    }
]

In my JavaScript code, I have an array [50, 20, 60, 40, 70, 80]. How can I construct a query to specifically choose the second object from the collection since my array includes all the numbers (40, 50, and 60) in its elements array?

Answer №1

One way to filter an array using mongoDB is by utilizing the Aggregation Set Operator. This involves finding the intersection of the given array with the database array and then checking for equality using the setEquals method. See the example query below:

db.collectionName.aggregate({
    "$project": {
        "checkAllElem": {
            "$setEquals": [{
                "$setIntersection": ["$items", [5, 2, 6, 4, 7, 8]]
            }, "$items"]
        },
        "items": 1
    }
}, {
    "$match": {
        "checkAllElem": true
    }
})

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

Run a series of promises in an array one after the other without relying on async and await

Imagine having an array filled with promises. Each element in this array represents a knex.js query builder that is prepared to be executed and generates a promise. Is there a way to execute each element of this dynamically built array sequentially? let ...

Stop browser rendering of HTML content when receiving a non-browser GET request

I am currently utilizing Node and Express to construct my application. Here is how my authentication function appears: exports.isAuthenticatedLocal = function(req, res, callback) { if (req.isAuthenticated()) { callback(null, true); } ...

What is the correct method for sending data through a POST request to a PHP script?

UPDATE: I made a mistake while trying to debug the issue. Instead of correctly debugging the AJAX POST request, I was double-clicking the .php file in the Network tab and assuming it was sending the same headers as the actual ajax POST request. This led me ...

Calculating mean values from nested documents

In this document structure, various engine information is stored including dates and definitions. I would like to aggregate the 'date' and 'definitions' fields of each engine without specifying a specific one. Here's an example of ...

Validating multiple input fields using Javascript

Initially, I must ensure that the ID and password textboxes are not empty (which is functioning correctly). Following that step, I need to verify on the same form that the ID entered in the textbox is a numeric value within the range of 3000 to 3999 (tha ...

What is the best way to retrieve the exact matched field values in MongoDB?

Below is a table I have created after writing the code for it. Please use organization db.test.insert({ bookname : "Mongodb", author : "Alex", price : 45, qty : 100}) db.test.insert({ bookname : "Cassandra", author : "John", price : ...

Leverage Vue3's v-html feature without the need for additional wrapping tags by using script

Is it possible to use Vue's v-html directive within a Vue 3 <script setup> setup without needing an additional wrapping tag? I am looking to achieve something similar to the following: <script setup> const html = ref(`<pre></pre& ...

Toggle menu using jQuery to show and hide options

I'm currently working on a menu that should open when the button is clicked once and close when clicked again. I had done this before but I seem to have forgotten how to achieve it. Here is the code snippet that I tried to use: var main = function() ...

When a named capture group is included in the regex of a GET path, Express crashes with the error message: "Cannot read property 'name' of undefined at Layer

I am looking to process a GET request and extract specific information from the URL. Let's consider this scenario: const REGEX_QUERY = /^\/?house\/(?<street>[a-z]+)\/(?<house>[0-9]+)$/i; const REGEX_QUERY_NO_NAMES = /^\ ...

Setting up Angular 2 application on Apache server

I just recently delved into the world of Angular 2 and successfully created my first demo angular application. I now want to make it accessible from anywhere by deploying it on a server. Following the instructions, I generated a build (dist) using the com ...

Ways to implement collapsible functionality into table rows

I have a table on my website and I want to initially display only 3 rows. When the user clicks on the 'more' button, I want the rest of the rows to be displayed. However, when I tried implementing this with code, I encountered rendering issues. I ...

The Google Maps API functions flawlessly on Chrome and Firefox, however, Internet Explorer seems to be having trouble running it

When using the Google Maps API, everything works fine on Chrome and Firefox but Internet Explorer encounters an issue. I am loading the API with jQuery and calling initialize(); The error message in IE6 states: error 'google' undefined function ...

JavaScript - All values stored from the for loop are registering as undefined

Recently delving into the realm of JavaScript programming, I find myself faced with a new challenge. While not my first language, this is one of my initial ventures with it. My current project involves creating a chess program utilizing the HTML5 canvas fe ...

AngularJS - Showcase a dynamic list of information according to the value chosen

Seeking assistance from anyone willing. I have data in JSON format structured like this { state1: [ member1, member2], state2: [ member3,member4...], ... } There is a dropdown that displays the states listed in the JSON data. When a state is selected, I ...

Utilize vanilla JavaScript to invoke the Angular factory

Struggling to find the right title for this query, I'm diving into Angular and using ngMaterial. Currently, I have a toast set up through an Angular factory. app.factory('notify', ['$mdToast', '$animate', function($mdToa ...

Why is it possible to import the Vue.js source directly, but not the module itself?

The subsequent HTML code <!DOCTYPE html> <html lang="en"> <body> Greeting shown below: <div id="time"> {{greetings}} </div> <script src='bundle.js'></script& ...

Utilizing knobs to dynamically incorporate components into templates on Storybook: A guide

I am a novice in the realm of storytelling, attempting to craft tales involving a basic button and a button adorned with icons. My objective is to have the ability to switch out the icons within the button utilizing the knobs section. For example: export c ...

Experiencing a problem with loading scenes on a splash screen using WebGL and three.js

As a newcomer to SOF, I apologize for not being familiar with local customs. // Hello all! I am attempting to develop a 3D model with a splash screen and first-person movement using three.js and its examples. // Here is the source: // The issue at hand ...

Struggling to find your way around the header on my website? Let me give

I'm looking to display certain links prominently at the top of a page, similar to this example: "home > page1 > link1 > article 1." Can someone advise on how to achieve this using HTML, PHP, or jQuery? ...

Fill an HTML div with JSON data obtained from a server

I am trying to display JSON data from a json-rpc server inside an HTML div. I can see the data in Chrome and Firefox dev tools, but I need it to be displayed within a specific div on the page. I have written a script to populate the 'mybox' div, ...