- 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
Getting distinct values from object array in MongoDB?
To get distinct values from object array in MongoDB, use distinct(). Let us create a collection with documents −
> db.demo442.insertOne( ... { ... ... "Information" : [ ... { ... "FirstName" : "John", ... "Age" : 21 ... }, ... { ... "FirstName" : "Sam", ... "Age" : 23 ... }, ... { ... "FirstName" : "John", ... "Age" : 24 ... }, ... { ... "FirstName" : "Carol", ... "Age" : 20 ... }, ... { ... "FirstName" : "Sam", ... "Age" : 22 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e78cf29bbc41e36cc3caeb8") }
Display all documents from a collection with the help of find() method −
> db.demo442.find();
This will produce the following output −
{ "_id" : ObjectId("5e78cf29bbc41e36cc3caeb8"), "Information" : [ { "FirstName" : "John", "Age" : 21 }, { "FirstName" : "Sam", "Age" : 23 }, { "FirstName" : "John", "Age" : 24 }, { "FirstName" : "Carol", "Age" : 20 }, { "FirstName" : "Sam", "Age" : 22 } ] }
Following is the query to get distinct values from object array in MongoDB −
> db.demo442.distinct("Information.FirstName");
This will produce the following output −
[ "Carol", "John", "Sam" ]
Advertisements