- Trending Categories
- 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
MongoDB query to get only distinct values
To get distinct values, use distinct() in MongoDB. It finds the distinct values for a specified field across a single collection or view and returns the results in an array.
Let us create a collection with documents −
> db.demo287.insertOne({"details":{"AllVowels":["a","u","u","o","e","a","o","i"]}}); { "acknowledged" : true, "insertedId" : ObjectId("5e4c014cf49383b52759cbbd") }
Display all documents from a collection with the help of find() method −
> db.demo287.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e4c014cf49383b52759cbbd"), "details" : { "AllVowels" : [ "a", "u", "u", "o", "e", "a", "o", "i" ] } }
Following is the query to get distinct values −
> db.demo287.distinct("details.AllVowels");
This will produce the following output −
[ "a", "e", "i", "o", "u" ]
Advertisements