$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

Please do not enter any spam link in the comment box.

Related Posts

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...