$addToSet operator in MongoDB

You are here : Home / MongoDB Tutorial


1) $addToSet operator in MongoDB.
$addToSet operator returns an array of all UNIQUE values in the group from collection in MongoDB.
2) Find all salary of all employee with same firstName in array from collection in MongoDB >


Step 1 - We will group employee by firstName and find all UNIQUE salary in each group.
Step 2- We will use aggregate() method, $group operator and  $addToSet operator
> db.employee.aggregate([{$group : {_id : "$firstName", salary_all : {$addToSet : "$salary"}}}])


Output >
{ "_id" : "ank", "salary_all" : [ 1000, 2000 ] }
{ "_id" : "sag", "salary_all" : [ 3000, 4000 ] }
{ "_id" : "neh", "salary_all" : [ 5000 ] }


3) Find all UNIQUE salary of all employee in array from collection in MongoDB >


Step 1 - We will group employee by null (nothing) and find all salary in group (there will be only 1 group - i.e. whole documents of collection)
Step 2- We will use aggregate() method, $group operator, $addToSet operator and _id : null
> db.employee.aggregate([{$group : {_id : null, salary_all : {$addToSet : "$salary"}}}])


Output >
{ "_id" : null, "salary_all" : [ 1000, 2000, 3000, 4000, 5000 ] }


4) How to write aggregate query with where clause in MongoDB >


Find all UNIQUE salary of all employee with same firstName where salary > 2000 in array from  collection in MongoDB >
Step 1 - We will find document where salary > 2000
Step 2 - We will use $match operator
Step 3 - Then we will group employee by firstName and find all salary in each group.
Step 4 - We will use aggregate() method, $group operator, and _id : null


> db.employee.aggregate([
 { $match: { salary : { $gt: 2000} } },
 {$group : {_id : "$firstName", salary_all : {$addToSet : "$salary"}}}])


Output >
{ "_id" : "sag", "salary_all" : [ 3000, 4000 ] }
{ "_id" : "neh", "salary_all" : [ 5000 ] }




Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.


RELATED LINKS>

What is MongoDB - A quick introduction to database

objectId in MongoDB

Create new database in mongoDB


eEdit
Must read for you :