Jul 4, 2016

$setEquals operator in MongoDB

This operator comes in MongoDB version 2.6, $setEquals compares the arrays and returns true or false. $setEquals returns true if arrays have same distinct element if they don’t then returns false.
  1. $setEquals treat to arrays like sets.
  2. $setEquals ignore duplicate entry in array.
  3. $setEquals ignore the order of elements.
  4. $setEquals evaluate at top level to nested array. 

Syntax:


{ $setEquals: [ <expression1>, <expression2>, ... ] }


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, setEle: { $setEquals: [ "$like", "$comment" ] }, _id: 0 } }
   ]
)


Result:


{ "like" : [ "Dilip", "Ashish" ], "comment" : [ "Dilip", "Ashish" ], "setEle" : true }
{ "like" : [ "Dilip", "Ashish" ], "comment" : [ "Dilip", "Dilip", "Ashish" ], "setEle" : true }
{ "like" : [ "Dilip", "Ashish" ], "comment" : [ "Dilip", "Mamta", "Ashish" ], "setEle" : false }
{ "like" : [ "Mahesh", "Vipul" ], "comment" : [ "Dilip", "Ashish" ], "setEle" : false }
{ "like" : [ "Mahesh", "Vipul" ], "comment" : [ [ "Mahesh", "Vipul" ] ], "setEle" : false }
{ "like" : [], "comment" : [], "setEle" : true }
{ "like" : [], "comment" : [ [] ], "setEle" : false }