Jul 4, 2016

$setIntersection operator in MongoDB

Its returns common elements appear in all input sets and accept any number of documents.

  1. $setIntersection takes only two  input expression
  2. $setIntersection treats like sets to arrays
  3. $setIntersection ignores the duplicates
  4. $setIntersection ignores the order of elements
  5. $setIntersection filters duplicates elements
  6. $setIntersection treats as element to nested array

Syntax:


{ $setIntersection: [ <array1>, <array2>, ... ] }


Example: Create a collection as following.


{_id:1,like:["Dilip","Ashish"],comment:["Dilip","Ashish"]}
{_id:2,like:["Dilip","Ashish"],comment:["Dilip","Dilip","Ashish"]}
{_id:3,like:["Dilip","Ashish"],comment:["Dilip","Mamta","Ashish"]}
{_id:4,like:["Mahesh","Vipul"],comment:["Dilip","Ashish"]}
{_id:5,like:["Mahesh","Vipul"],comment:[["Mahesh","Vipul"]]}
{_id:6,like:[],comment:[]}
{_id:7,like:[],comment:[[]]}


Run following query


db.LikeAndComment.aggregate(
   [
     { $project: { like: 1, comment: 1, eleIntersect: { $setIntersection: [ "$like", "$comment" ] }, _id: 0 } }
   ]
)


Result:


{ "like" : [ "Dilip", "Ashish" ], "comment" : [ "Dilip", "Ashish" ], "eleIntersect" : [ "Dilip", "Ashish" ] }
{ "like" : [ "Dilip", "Ashish" ], "comment" : [ "Dilip", "Dilip", "Ashish" ], "eleIntersect" : [ "Dilip", "Ashish" ] }
{ "like" : [ "Dilip", "Ashish" ], "comment" : [ "Dilip", "Mamta", "Ashish" ], "eleIntersect" : [ "Dilip", "Ashish" ] }
{ "like" : [ "Mahesh", "Vipul" ], "comment" : [ "Dilip", "Ashish" ], "eleIntersect" : [] }
{ "like" : [ "Mahesh", "Vipul" ], "comment" : [ [ "Mahesh", "Vipul" ] ], "eleIntersect" : [] }
{ "like" : [], "comment" : [], "eleIntersect" : [] } /* 7 */ { "like" : [], "comment" : [ [] ], "eleIntersect" : [] }