Jul 7, 2016

$setIsSubset operator in MongoDB

Its returns true or false, $setIsSubset accepts only two argument expression only and returns true if all elements of first expression belong to second expression.
  1. $setDifference treats like sets to arrays
  2. $setDifference ignores the duplicates
  3. $setDifference ignores the order of elements
  4. $setDifference filters duplicates elements
  5. $setDifference treats as element to nested array

Syntax:


{ $setIsSubset: [ <expression1>, <expression2> ] }


Example:


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


Run following query


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


Result:


{ "like" : [ "Dilip", "Ashish" ], "comment" : [ "Dilip", "Ashish", "Mamta" ], "eleSub" : true }
{ "like" : [ "Dilip", "Ashish" ], "comment" : [ "Dilip", "Dilip", "Ashish", "Raj" ], "eleSub" : true }
{ "like" : [ "Dilip", "Ashish" ], "comment" : [ "Dilip", "Mamta", "Ashish" ], "eleSub" : true }
{ "like" : [ "Mahesh", "Vipul" ], "comment" : [ "Dilip", "Ashish" ], "eleSub" : false }
{ "like" : [ "Akash" ], "comment" : [ [ "Ravi" ] ], "eleSub" : false }