- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get distinct levels of array field in MongoDB?
To get distinct levels of array field, use $addToSet in MongoDB. Let us create a collection with documents −
> db.demo122.insertOne({"ListOfValues":[100,10]}); { "acknowledged" : true, "insertedId" : ObjectId("5e2f20f1140daf4c2a3544b6") } > db.demo122.insertOne({"ListOfValues":[240,10]}); { "acknowledged" : true, "insertedId" : ObjectId("5e2f20f7140daf4c2a3544b7") }
Display all documents from a collection with the help of find() method −
> db.demo122.find();
This will produce the following output −
{ "_id" : ObjectId("5e2f20f1140daf4c2a3544b6"), "ListOfValues" : [ 100, 10 ] } { "_id" : ObjectId("5e2f20f7140daf4c2a3544b7"), "ListOfValues" : [ 240, 10 ] }
Following is the query to get distinct levels of array field in MongoDB −
> db.demo122.aggregate([ ... { ... "$group": { ... "_id": 0, ... "ListOfValues": { "$addToSet": "$ListOfValues" } ... } ... } ... ])
This will produce the following output −
{ "_id" : 0, "ListOfValues" : [ [ 240, 10 ], [ 100, 10 ] ] }
Advertisements