Unable to implement $addToSet in MongoDB to fetch values of a single field?


The $addToSet operator adds value to an array unless the value is already present, in which case $addToSet does nothing to that array.

Let us create a collection with documents −

> db.demo533.insertOne({"ProjectName":"Online Hospital Management"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b4cfaef4dcbee04fbbbfc")
}
> db.demo533.insertOne({"ProjectName":"Online Library Management"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b4d02ef4dcbee04fbbbfd")
}
> db.demo533.insertOne({"ProjectName":"Online Hospital Management"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b4d04ef4dcbee04fbbbfe")
}
> db.demo533.insertOne({"ProjectName":"Online Customer Tracker"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b4d0def4dcbee04fbbbff")
}

Display all documents from a collection with the help of find() method −

> db.demo533.find();

This will produce the following output −

{ "_id" : ObjectId("5e8b4cfaef4dcbee04fbbbfc"), "ProjectName" : "Online Hospital Management" }
{ "_id" : ObjectId("5e8b4d02ef4dcbee04fbbbfd"), "ProjectName" : "Online Library Management" }
{ "_id" : ObjectId("5e8b4d04ef4dcbee04fbbbfe"), "ProjectName" : "Online Hospital Management" }
{ "_id" : ObjectId("5e8b4d0def4dcbee04fbbbff"), "ProjectName" : "Online Customer Tracker" }

Following is the query to implement $addToSet and fetch the values of field ProjectName −

> db.demo533.aggregate(
...    [
...       {
...          $group:
...          {
...             _id:null,
...             SetOfProject: { $addToSet: "$ProjectName" }
...          }
...       }
...    ]
... )

This will produce the following output −

{ "_id" : null, "SetOfProject" : [ "Online Customer Tracker", "Online Library Management", "Online Hospital Management" ] }

Updated on: 14-May-2020

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements