Request one field equal to another field in the array?

Suppose a set like this:

{
   movie : 1,
   List : [ 1 , 2 ,5 , 6 ]
},
{
   movie : 2,
   List : [ 3, 5, 7 ]
},
{
   movie : 3,
   List : [ 1, 3, 6 ]
}

I want to get all the documents that the "movie" exists in the "list".

How to write a query or aggregate?

+4
source share
1 answer

The ideal form of this is with native operators using .aggregate()with $redact:

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

Or, if you don't have $redactone available in your version of MongoDB, use the query condition instead $where:

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

Both have a basic approach for finding the value of a single field present in an array field in a document.

, $redact, , $anyElementTrue:

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

MongoDB 3.2:

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

$map ["$movie"] /, $setIsSubset. $map , true/false, true/false $anyElementTrue.

+1