Is it possible to match a field with an array field in a query?

Imagine having a collection structured like this:

{
   film : 1,
   Items : [ 1 , 2 ,5 , 6 ]
},
{
   film : 2,
   Items : [ 3, 5, 7 ]
},
{
   film : 3,
   Items : [ 1, 3, 6 ]
}

I am looking to retrieve all entries where the 'film' is included in the 'Items' list.

Can you advise on how to formulate the query or aggregate for this?

Answer №1

To achieve this effectively, the recommended method is to utilize native operators like .aggregate() along with $redact:

db.collection.aggregate([
  { "$redact": {
    "$cond": {
      "if": {
        "$setIsSubset": [
          { "$map": { "input": ["A"], "as": "el", "in": "$movie" } },
          "$List"
        ]
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])

If $redact is not available in your MongoDB version, another alternative is to use the $where query condition:

db.collection.find(function() {
  return this.List.indexOf(this.movie) != 1
})

Both methods focus on checking for one field value within an array field in the document.

Variations of using $redact are possible, such as incorporating $anyElementTrue:

db.collection.aggregate([
  { "$redact": {
    "$cond": {
      "if": {
        "$anyElementTrue": {
          "$map": {
            "input": "$List",
            "as": "el",
            "in": { "$eq": [ "$$el", "$movie" ] }
          }
        }
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])

Alternatively, a concise syntax can be used in MongoDB 3.2:

db.collection.aggregate([
  { "$redact": {
    "$cond": {
      "if": {
        "$setIsSubset": [
          ["$movie"],
          "$List"
        ]
      },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])

In this case, similar to the original implementation utilizing $map, the ["$movie"] converts the single element into an array/set for comparison with $setIsSubset. The latter example uses $map to apply conditions to each element in the array, generating an array of true/false values that are consolidated into a logical outcome via $anyElementTrue.

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

Developing a TypeScript Library from Scratch

After following the instructions on this particular website, I have implemented the following JavaScript code: function A(id) { var about = { Version: "0.0.0.1", }; if (id) { if (window === this) { return new A(i ...

Organizing classes under namespaces in Node.js

Currently working on a project in node.js. I have several related classes that I want to organize in a subdirectory, with one class per file structured like this: lib/ main.js melons/ casaba.js cantaloupe.js carnegie.js I plan to us ...

React component failing to render even when event is triggered

For my latest project, I am creating a blog using react, next.js, and json-server. The blog is coming along nicely with dynamically loaded blog posts and UI elements. However, I've hit a roadblock when it comes to loading comments dynamically. The sp ...

Navigating between pages using React-router-dom

Just implemented a simple navigation using react-router-dom. Managed to get it working with this.props.history.push('/pathName'); But I'm not entirely sure if my understanding and approach are correct. Any advice on correcting my mistakes wo ...

Using jQuery.ajax() to capture and log the details of an HTTP request

I have a function that makes an HTTP POST request and I would like to log it for debugging purposes. Here is the code: function sendPostRequest(URL, DATA, callback) { $.ajax({ url: URL, type: "POST", dataType: "text", c ...

Is it possible for search engines like google to index Javascript content that is stored within divs and loaded onto the page?

My website utilizes JavaScript to dynamically add content to div elements, like so: <script> //This content is generated by PHP var contents = [ "Item 1", "Item 2" ]; //Display the first item document.getElementById( "item" ).textCo ...

What is the best way to end a table row after every group of four items?

I am working with a Handlebars template to display an array of movies in a table with four columns. Currently, I have set up a HBS helper in my code: app.engine('handlebars',exphbs({ defaultLayout: 'main', helpers: { n ...

JavaScript: abbreviated way to selectively append an element to an array

Currently, I am in the process of creating a Mocha test for a server at my workplace. When dealing with customer information, I receive two potential phone numbers, with at least one being defined. var homePhone = result.homePhone; var altPhone = ...

"Surprising outcomes when using the splice method on an array

Exploring the functionalities of Array.splice(). deleteCount: A whole number indicating the quantity of old array elements to eliminate. Understood. It seems clear. I aim to extract the final 4 items in the array. I trust that refers to elements? arr. ...

What is the best way to verify the existence of a user and password in a MongoCollection before setting it in

How can I verify if the credentials entered in the login form exist in the database collection or not? String username = request.getParameter("user"); String password = request.getParameter("pass"); String[] rememberusr = request.getParameterValues("rem ...

Trouble with linking an external JavaScript file in HTML document

I'm having some trouble including an external JavaScript file in my HTML. I followed the steps but the pie chart is not showing up as expected. Can someone please take a look and let me know if I missed anything? Here's the link to where I got th ...

An unexpected issue occurred: AngularJS module error prevented from functioning properly

I'm attempting to set up a Modal popup when an image is clicked using Bootstrap Lightbox, but I can't seem to get it working. I've followed an example with the exact same code provided below. I have downloaded the Lightbox components (*.ligh ...

Mongodb Retrieving results and their opposites

Can you retrieve results that match a specific query and those that do not in a single query? Assume I have the following data: { name: 'name1', age: 19 }, { name: 'name2', age: 20 }, { name: 'name3', ...

Encountering a problem during npm installation, where an error occurs due to being unable to read the property "match"

I'm encountering significant challenges when trying to install packages using npm. The output log I'm receiving is not helping me at all, and I'm unsure of where or how to address this issue. 0 info it worked if it ends with ok 1 verbose cli ...

Top method for identifying browser window modifications such as navigating back, altering the URL, refreshing, or closing the window

Currently, I am developing a testing application that requires me to trigger a finsihTheTest() function in specific situations. These situations include: When the user attempts to reload the page. When the user tries to navigate back from the page. If the ...

The array element is not being shown in the id "main" when using a for loop with the onchange function

I've been using document.write to display specific content, but it seems to be removing other elements from the page. Is there a way for me to display this loop inside the element with id="main" without losing any content? When I attempt to use docume ...

The issue arises when DataTable fails to retrieve the ID element following a page transition

I am facing an issue with making ajax calls on focus for each text input. I am able to do it on the first page, during document ready event. However, when I navigate to another page, JavaScript is unable to parse the inputs as they were not created during ...

css background is repeating after the height of the div is reset

I'm working on a project where I want to resize an image while maintaining its aspect ratio to fit the height/width of the browser window. However, every time the code for resizing is implemented, the div height continues to increase with each resize ...

The challenge of accessing controllerAs variables/objects in AngularJS custom directives

After deciding to refactor my code and move DOM manipulation and functions into directives instead of controllers, I encountered an issue with accessing variables/objects defined using the controllerAs 'this' syntax. Despite trying to use bindToC ...

Is it possible to have Vue.js code within a v-for loop in such a way that it executes every time the v-for loop runs?

<div class="questions" v-for="(q,index) in questions " :key="index" {{this.idx+=1}} > <h3 > {{q.content}}</h3> <h3> A) {{q.a}} </h3> <h3> B) {q.b}} </h3> ...