Jul 4, 2016

$setUnion in MongoDB

$setUnion returns the all element set appears in input sets and accept any number of expression.
  1. $setUnion accepts any number of expressions.
  2. $setUnion ignores duplicate elements in sets.
  3. $setUnion ignores order o elements.
  4. $setUnion treat as elements 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, eleUnion: { $setUnion: [ "$like", "$comment" ] }, _id: 0 } }
   ]
)


Result:


{ "like" : [ "Dilip", "Ashish" ], "comment" : [ "Dilip", "Ashish" ], "eleUnion" : [ "Dilip", "Ashish" ] }
{ "like" : [ "Dilip", "Ashish" ], "comment" : [ "Dilip", "Dilip", "Ashish" ], "eleUnion" : [ "Dilip", "Ashish" ] }
{ "like" : [ "Dilip", "Ashish" ], "comment" : [ "Dilip", "Mamta", "Ashish" ], "eleUnion" : [ "Dilip", "Ashish", "Mamta" ] }
{ "like" : [ "Mahesh", "Vipul" ], "comment" : [ "Dilip", "Ashish" ], "eleUnion" : [ "Mahesh", "Ashish", "Vipul", "Dilip" ] }
{ "like" : [ "Mahesh", "Vipul" ], "comment" : [ [ "Mahesh", "Vipul" ] ], "eleUnion" : [ "Mahesh", "Vipul", [ "Mahesh", "Vipul" ] ] }
{ "like" : [], "comment" : [], "eleUnion" : [] }
{ "like" : [], "comment" : [ [] ], "eleUnion" : [ [] ] }