Introduction to MongoDB $setIsSubset Operator

$setIsSubset operator is an array operator in MongoDB, used to determine if an array is a subset of another array, and returns a Boolean value.

Syntax

The syntax of the $setIsSubset operator is as follows:

{ $setIsSubset: [ <subset>, <superset> ] }

where <subset> and <superset> are two arrays, <subset> represents the array to be tested, and <superset> represents the array being tested against, and returns a Boolean value.

Use Cases

The $setIsSubset operator is typically used to determine if an array contains all the elements of another array, for example:

  • Determine if a user has certain permissions.
  • Determine if a movie belongs to a list of movies.

Examples

The following example demonstrates how to use the $setIsSubset operator to determine if an array is a subset of another array.

Example Data

We have two arrays:

db.movies.insertMany([
  {
    title: "The Shawshank Redemption",
    genres: ["Drama", "Crime"]
  },
  {
    title: "The Dark Knight",
    genres: ["Action", "Crime", "Drama"]
  }
])

Example Code

The following example demonstrates how to use the $setIsSubset operator to determine if an array is a subset of another array:

db.movies.aggregate([
  {
    $match: {
      $expr: {
        $setIsSubset: [["Drama", "Crime"], "$genres"]
      }
    }
  }
])

Example Result

After running the above example code, the aggregation result will contain the following documents:

{
  "_id" : ObjectId("..."),
  "title" : "The Shawshank Redemption",
  "genres" : [ "Drama", "Crime" ]
}
{
  "_id" : ObjectId("..."),
  "title" : "The Dark Knight",
  "genres" : [ "Action", "Crime", "Drama" ]
}

Since ['Drama', 'Crime'] is a subset of ['Drama', 'Crime', 'Action'], the above aggregation operation will return all movies that contain the Drama and Crime genres.

Conclusion

The $setIsSubset operator is a useful array operator in MongoDB, used to determine if an array is a subset of another array. When using the $setIsSubset operator, it is important to note the order of the subset and superset, passing the subset as the first argument to the operator and the superset as the second argument to the operator.