How can I use an input array to filter data in mongodb?

When receiving input from the front-end, it looks like this:

{
"options":[
      {
          "optionId":"5ebbe0f56b197f36fc472168"
      },
      {
           "optionId":"5ebbe1aa6b197f36fc47216e"
      }
]

}

The goal is to filter the data in a way that results in an array of objects containing both of these IDs. Here is the data structure to search through:

"answersArray" : [
    {
        "_id" : ObjectId("5ede62f6a6979e5128bb89ba"),
        "questionId" : ObjectId("5ebbe00e6b197f36fc472161"),
        "answerId" : ObjectId("5ebbe00e6b197f36fc472162")
    },
    {
        "_id" : ObjectId("5ede62f6a6979e5128bb89b9"),
        "questionId" : ObjectId("5ebbe0f56b197f36fc472168"),
        "answerId" : ObjectId("5ebbe0f56b197f36fc472169")
    },
    {
        "_id" : ObjectId("5ede62f6a6979e5128bb89b8"),
        "questionId" : ObjectId("5ebbe1aa6b197f36fc47216e"),
        "answerId" : ObjectId("5ebbe1aa6b197f36fc47216f")
    }
],

"answersArray" : [
    {
        "_id" : ObjectId("5ede620ea6979e5128bb89b5"),
        "questionId" : ObjectId("5ebbd4e76b197f36fc47211e"),
        "answerId" : ObjectId("5ebbd4e76b197f36fc47211f")
    },
    {
        "_id" : ObjectId("5ede620ea6979e5128bb89b4"),
        "questionId" : ObjectId("5ebbd5516b197f36fc472120"),
        "answerId" : ObjectId("5ebbd5516b197f36fc472121")
    },
    {
        "_id" : ObjectId("5ede62f6a6979e5128bb89b8"),
        "questionId" : ObjectId("5ebbe1aa6b197f36fc47216e"),
        "answerId" : ObjectId("5ebbe1aa6b197f36fc47216f")
    },

]

The expected answer should be:

 "answersArray" : [
    {
        "_id" : ObjectId("5ede62f6a6979e5128bb89ba"),
        "questionId" : ObjectId("5ebbe00e6b197f36fc472161"),
        "answerId" : ObjectId("5ebbe00e6b197f36fc472162")
    },
    {
        "_id" : ObjectId("5ede62f6a6979e5128bb89b9"),
        "questionId" : ObjectId("5ebbe0f56b197f36fc472168"),
        "answerId" : ObjectId("5ebbe0f56b197f36fc472169")
    },
    {
        "_id" : ObjectId("5ede62f6a6979e5128bb89b8"),
        "questionId" : ObjectId("5ebbe1aa6b197f36fc47216e"),
        "answerId" : ObjectId("5ebbe1aa6b197f36fc47216f")
    }
],

Any suggestions on how to achieve this filtering?

Answer №1

To meet your requirements, consider utilizing the $all operator.

db.collection.findOne(
    {
        "answersArray.questionId": {$all: options.map(id => ObjectId(id))}
    }
);

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

The attempt to update several partial views using Jquery, MVC, and Json is currently malfunctioning

I am facing issues with updating multiple partial views using jQuery, MVC, and JSON. The partial views on my page are not getting updated. Below is the code for my view: Here is the code for my controller: public class GetStudentsController : Controlle ...

Exporting variables in Angular's Ahead of Time (AoT) compiler is

I recently attempted to incorporate dynamic configuration into my project, following a guide I found in this insightful post. While everything functions smoothly with the JiT compiler, I encountered the following error when attempting to build using the A ...

Tips for passing props while clicking on a v-data-table:

I am currently facing an issue in my app while using v-data-table. I am able to pass props with an extra slot, but I want the entire row to be clickable in order to open a dialog with the prop item: <template v-slot:item.actions="{ item }"> ...

extracting data from a javascript array

While facing an issue with scraping a website , I received helpful solutions from Fatherstorm and marcog. Despite the great solution provided by Fatherstorm, there were some minor bugs related to start time and the number of image sources being retrieved a ...

Tips for resolving the ExtPay TypeError when using Typscript and Webpack Bundle

I am currently trying to install ExtPay, a payment library for Chrome Extension, from the following link: https://github.com/Glench/ExtPay. I followed the instructions up until step 3 which involved adding ExtPay to background.js. However, I encountered an ...

Having trouble with a JavaScript Promise that seems to be stuck in limbo

I have developed two custom promises that are quite similar, with the only difference being that they operate on distinct user inputs. Both promises utilize various classes and methods from Google Maps API v-3. What's puzzling is that when the first ...

What is the best way to capture a form submission when there are no errors?

My form includes a validation check for valid fields upon submission. Here is an example of how it is structured: <form class="form-horizontal" method="post" action="#" name="basic_validate" id="basic_validate" /> <div class="con ...

Generating an associative array within a loop

Good day! I have successfully created an array using a for loop. Initially, the array is empty until it goes through the loop. Now, I am looking to include an associative array in my existing setup. Currently, this is how my array looks: [0] => Array ...

PHP/MySQL clarification regarding time slots

Could someone assist me with this discussion I found? Due to my low reputation, I am unable to comment for further clarification. Although I grasp the solution provided in the mentioned discussion, I am struggling to comprehend how to pass the data to my ...

Having trouble with state not updating correctly after making a fetch request within a useEffect hook in

In my React app with an Express backend, I am facing a challenge in updating the component state using the useEffect hook to trigger once when the component renders. Inside the useEffect, I fetch data from the Express server. const Favorites = ({ user }) = ...

Can someone assist me with running queries on the MongoDB collection using Node.js?

In my mongodb collection called "jobs," I have a document format that needs to display all documents matching my query. { "_id": { "$oid": "60a79952e8728be1609f3651" }, "title": "Full Stack Java Develo ...

The schema configuration is invalid: The type `S` is not recognized in path `0` of the mongodb dataset

I am working on creating a collection with schema in MongoDB and ExpressJS, but an error is occurring: Invalid schema configuration: S is not a valid type at path 0. See for a list of valid schema types. What steps should be taken to resolve this issue? ...

How can I vertically align a photo or image on Facebook?

Can anyone explain how Facebook manages to vertically align its photos without using padding or margins? I've looked into their img tag and its parent, but neither seem to have any spacing properties. Although there is a vertical-align attribute prese ...

JavaScript effectively divides multiple child dropdowns with the main dropdown, thanks to Bootstrap innovation

I have implemented a jQuery function to dynamically change multiple child dropdowns based on the selected value of the main dropdown. For reference, you can view the image here. However, I encountered an issue when applying the Bootstrap styles "form-con ...

Failed commitments in JavaScript without a catch block (unhandled rejection)

When working on my project in VueJs JavaScript, I want to be able to see console messages if any of my Promises are not fulfilled and do not have a catch block. I attempted using the following code: Promise.reject("error!"); window.addEventListener(&apos ...

Tips on showcasing a nested array in Next.js or converting it into an object

{ "count": 2, "rows": [ { "id": "5ab46e31-391c-46a7-8e45-db9ada07626d", "name": "admin", "email": "<a href="/cdn-cgi/l/email-p ...

Mongo DB's $set operation fails to update the req.body object

app.put('/accountlist/:id', function (req, res) { var id = req.params.id; console.log(req.body)); db.accounts.findAndModify({ query: {_id: mongojs.ObjectId(id)}, update: {$set:req.body}}, new: true}, function (err, ...

Tips for incorporating several form input outputs into an array State in React

I am an aspiring coder diving into the world of React by working on a simple app that helps calculate how much money one has, designed for my kids to use and learn from. The app consists of 5 components, each with its own input field. These fields allow us ...

Generate a custom Elementor shortcode dynamically using JavaScript

I have a custom-built website using WordPress and Elementor. I am running code through the html element in Elementor to display dropdown menus. When a value is selected from each dropdown and the button is clicked, the values are stored in variables and th ...

Is there a problem with addEventListener returning false?

What does keeping the third parameter as false in the line below signify? var el = document.getElementById("outside"); el.addEventListener("click", modifyText, false); ...