

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" ] }
- Related Questions & Answers
- Fetch specific field values in MongoDB
- How to select a single field in MongoDB?
- MongoDB query to fetch array values
- MongoDB query for a single field
- MongoDB $addToSet to add a deep nested array of object?
- MySQL query to fetch only a single field on the basis of boolean value in another field
- Opposite of $addToSet to '$removeFromSet' in MongoDB?
- Implement MongoDB $addToSet for an array in an array and append a value
- Use LIKE % to fetch multiple values in a single MySQL query
- MongoDB aggregation to fetch documents with specific field value?
- MongoDB query to limit the returning values of a field?
- Selecting only a single field from MongoDB?
- How to compare field values in MongoDB?
- How to update a single field in a capped collection in MongoDB?
- MongoDB query to implement nor query to fetch documents except a specific document
Advertisements