Introduction to MongoDB $setDifference Operator

MongoDB is a non-relational database that provides many query and aggregation operators to help developers better handle data. The $setDifference operator is one useful operator that is used to get the different elements between two collections.

The $setDifference operator is used to get the different elements between two arrays. The operator returns a new array that contains the elements that appear in the first array but not in the second array.

Syntax

The syntax of the $setDifference operator is as follows:

{ $setDifference: [ <array1>, <array2> ] }

Where <array1> and <array2> are the two arrays to be compared. The operator will return the elements that appear in the first array but not in the second array.

Use Cases

The $setDifference operator is commonly used in the following use cases:

  • Getting the difference between two arrays
  • Using in aggregation pipeline

Examples

Assume there is a collection named students that contains the names and courses selected by students. Now we want to get the names of all students who did not choose a specific course. The $setDifference operator can be used to solve this problem.

Here is an example data:

{ "name": "Alice", "courses": ["Math", "Physics"] }
{ "name": "Bob", "courses": ["Physics", "Chemistry"] }
{ "name": "Charlie", "courses": ["Math", "Chemistry"] }

Now we want to get the names of students who did not choose the “Physics” course. The following aggregation pipeline can be used:

db.students.aggregate([
  { $project: { _id: 0, name: 1 } },
  { $setDifference: ["$courses", ["Physics"]] }
])

After running the above aggregation pipeline, the following result will be returned:

{ "name": "Alice", "courses": ["Math", "Physics"] }
{ "name": "Charlie", "courses": ["Math", "Chemistry"] }

In the example above, the $project operator is used to select only the name field from the document. Next, the $setDifference operator is used to get the names of students who did not choose the “Physics” course.

Conclusion

The $setDifference operator is a useful operator that can be used to get the different elements between two arrays. It is commonly used to get data that meets specific conditions in an aggregation pipeline.