$setDifference operator in mongodb

It’s accept only two argument expression and returns the set of element who appears in first not in second

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


Syntax:


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


Example: Create a Collection as following


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


Run Following setDifference query


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


Result:



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

No comments:

Post a Comment

PostgreSQL: How to change the password of the user

This article will teach you to change the password of the user in PostgreSQL. To change the password, we use the ALTER ROLE, its uses are ...