Count the number of elements in a MongoDB array using a

Sample Collection

[
 {
  items: [
   {name: 'apple'}, {name: 'mango'}, {name: 'orange'}
  ]
},
 {
  items: [
   {name: 'banna'}, {name: 'grapes'}, {name: 'orange'}
  ]
}
]

I am looking for a query that can determine which document contains at least two of the searched products.

For example..

collection.find({ items: {$in: ['apple', 'mango', 'durian', 'avocado', 'orange']} })

The current query only checks if it contains one of those products. I want to identify documents that have at least two of the searched products in them.

Answer №1

To modify the query structure, you can add specific code or utilize an aggregation pipeline.

For Option 1 (recommended), implement the aggregation pipeline with $filter:

let fruits = ['apple', 'mango', 'durian', 'avocado', 'orange'];
collection.aggregate([
    {
        $match: {
            "products.name": {$in: fruits}
        }
    },
    {
        $project: {
            good_products_size: {
                $size: {
                    $filter: {
                        input: "$products",
                        as: "product",
                        cond: {$in: ["$$product.name", fruits]}
                    }
                }
            }
        }
    },
    {
        $match: {
            good_products_size: {$gt: 1}
        }
    }
]);

Alternatively, for Option 2 (less recommended in my opinion), you can generate all possible pairs from the fruits array and utilize $all:

let fruits = ['apple', 'mango', 'durian', 'avocado', 'orange'];
let queryOrConds = [];

for (let i = 0; i < fruits.length - 1; i++) {
    for (let j = i; j < fruits.length - 1; j++) {
        queryOrConds.push({"products.name": {$all: [fruits[i], fruits[j]]}})
    }
}
collection.find({ $or: queryOrConds })

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

I am struggling to add a list from these nested functions in Express, but for some reason, the items are not being properly

I am currently working with three nested functions and facing an issue where the last function is not returning the desired list of items. Interestingly, when I log the results of the last function within the loop, I can see the URLs that I need. However, ...

utilizing loop to incorporate javascript callback

I am just starting to learn about asynchronous programming and I'm facing a challenge that I can't seem to solve. In my node.js app, I am working on serving stock quotes. The task involves querying a database for details of various companies, sen ...

"JavaScript/TypeScript: The Importance of Defining Object Return Types

While going through the Tour of Heroes tutorial for Angular, I found this method of returning an object to be confusing. createDb() { const heroes = [ { id: 11, name: 'Dr Nice' }, { id: 12, name: 'Narco' }, { id: 13, name: &a ...

Retrieving a file stored in MongoDB through GridFS using JavaScript in Node.js

Using MongoDB with JavaScript, I successfully inserted a file of any extension using GridFS. The file is stored as fs.chunks and fs.files. Now, my issue arises when trying to read the file's stream. Each time I attempt a read operation on gridStore, a ...

Reveal the functions of one module to another module

I have a node application that needs to retrieve the path to a folder and read all the files within it. For example: moduleA -server.js -controller --load.js Within load.js, there is a method (loadFolderFiles) which takes a file path as input and ...

Is it possible to create multiple inputs by clicking the div multiple times?

Having trouble figuring this out. The issue is that when I click on a div in the function playerMove(), it should assign the clicked ID to a variable. It works fine when I click on two different divs, but if I click on the same div twice, the variable valu ...

Facing difficulty in uploading image to local server using Froala editor

For testing purposes, I've been attempting to upload images using the Froala WYSIWYG editor on my localhost, but unfortunately, it's not functioning as expected. After selecting an image to upload, it briefly appears faded in the editor and then ...

Developing node.js scripts for configuring an app via the command line interface

file: /config/index.js; var config = { local: { mode: 'local', port: 3000 }, staging: { mode: 'staging', port: 4000 }, production: { mode: 'production', port ...

Having trouble sending a JavaScript variable to PHP using Ajax

I have a challenge where I need to pass values of a JavaScript variable to a PHP page and use those values there. However, when I do this, it returns a new HTML page that displays an error message saying "some error". Unfortunately, I cannot figure out why ...

Using Javascript to dynamically add form fields based on the selection made in a combo box

I am in the process of creating an information submission page for a website, where various fields will need to be dynamically generated based on the selection made in a combo box. For example, if the user selects "2" from the combo box, then two addition ...

Picture navigation tool

Looking for a way to create a side navigating menu bar using HTML and CSS? The challenge is wanting the menu items to only appear after clicking on a small image positioned at the top left corner of the page, which happens to be my website logo. Does anyo ...

Trouble connecting to MySQL database using Sequelize in Node.js

I am delving into Node.js and attempting to establish a connection with Sequelize by following the guidelines provided in its documentation (). Below is my db.js file: const Sequelize = require('sequelize') const db = new Sequelize('chat&a ...

Modify the href link before submitting the request

Here is the code snippet that I am working with : <a class="myLink" href='http://www.website.it/'>Link</a> <script type="text/javascript"> var stringToSend = ""; $('.myLink').click(function() { string ...

Node.js express version 4.13.3 is experiencing an issue where the serveStatic method is not properly serving mp3 or

I am currently utilizing Express 4.13.3 along with the serve-static npm module to serve static assets successfully, except for files with mp3 or ogg extensions. Despite reviewing the documentation, I have not come across any information indicating that thi ...

Tips for aligning an element with another element's position

Is it possible to have the new hello button displayed in exactly the same position as the previous one after clicking the Hello button? const rightDiv = document.querySelector('#rightDiv'); const leftButton = document.querySe ...

Transform the MongoDB data in the aggregation pipeline following the $addToSet stage: one set will serve as the keys, while the other set

As of now, my pipeline appears like this: db.getCollection("Members").aggregate( [ { "$match" : { "member.MemberInfo.BusinessUnitCode" : "20" } }, { "$group" : { "_id" : "$_id", " ...

Hovering over a Raphael animation - What's preventing it from functioning?

I'm currently working on a pie chart using Raphael, and I want to add a tooltip that displays text when hovering over a specific segment of the chart. The hover event is functioning correctly, but I'm having trouble adjusting the tooltip text coo ...

Retrieve all elements from an array using jQuery

How do I extract all the elements from the array outside of the function? $.each(Basepath.Templates, function(i){ templateArray = new Array({title: Basepath.Templates[i].Template.name, src: 'view/'+Basepath.Templates[i].Template.id, descri ...

Google Sheets - Create a randomized list of numerical values (specified quantity) within a certain range (set numbers) that collectively equal a specific total

Here is an interesting challenge... I am trying to find a way to generate a specific number of random values within a range that add up to a predetermined total in Google Sheets. For example, I want to create a list of 10 numbers that sum up to 100, with ...

The error message "Uncaught SyntaxError: Unexpected number" indicates a problem with

Check out my code below: var myVar = setInterval(myTimer, 500); function myTimer() { xhttp=new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { x ...