Union Intersection and Difference in MongoDB

In the official MongoDB documentation some special purpose implementation/examples of aggregation (union, intersect or minus/difference) are available. But the very simple cases are not described in detail. So decided to write it here so that it can help others too.
For all the examples I am going to use the below document:

MongoDB union

u

Union of pagecolor, headcolor: [“red”,”green”,”blue”,”black”]

The output will be:

1. $setUnion returns a set with elements that appear in any of the input sets.
2. It accepts any number of arguments.
3. Remember $setUnion always works on arrays.
4. $setUnion does not work on nested arrays. It works from the top level.

MongoDB Intersection

i

Intersection of pagecolor, headcolor: [“red”,”green”]

The output will be:

1. $setIntersection returns a set with elements that appear in all of the input sets.
2. Like $setUnion It also accepts any number of argument expressions.
3. It ignores duplicate entry and order of elements
4. Like $setUnion, $setIntersection also does not work on nested arrays. It works from the top level.

Symmetric Difference

sd

Symmetric Difference of pagecolor, headcolor: [“blue”,”black”]

The output will be:

1. $setDifference performs set operation on arrays, treating arrays as sets.
2. It ignores the duplicate entries and the order of the elements.
3. Like $setUnion, $ setDifference also does not work on nested arrays. It works from the top level.

Arijit Naskar

Arijit Naskar is a Software Developer and QA, also founder of alltechstories.com a popular tech tutorial & how-to website since 2014. He loves to explore new technologies and writing blogs.

You may also like...