- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 values from a column in MongoDB?
To get distinct values from a column, use distinct() in MongoDB. Let us first create a collection with documents −
> db.demo128.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e30583d68e7f832db1a7f5d") } > db.demo128.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e30584068e7f832db1a7f5e") } > db.demo128.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e30584368e7f832db1a7f5f") } > db.demo128.insertOne({"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e30584668e7f832db1a7f60") } > db.demo128.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e30584c68e7f832db1a7f61") }
Display all documents from a collection with the help of find() method −
> db.demo128.find();
This will produce the following output −
{ "_id" : ObjectId("5e30583d68e7f832db1a7f5d"), "Name" : "Chris" } { "_id" : ObjectId("5e30584068e7f832db1a7f5e"), "Name" : "David" } { "_id" : ObjectId("5e30584368e7f832db1a7f5f"), "Name" : "David" } { "_id" : ObjectId("5e30584668e7f832db1a7f60"), "Name" : "Bob" } { "_id" : ObjectId("5e30584c68e7f832db1a7f61"), "Name" : "Chris" }
Following is the query to get distinct values from a column in MongoDB −
> db.demo128.distinct("Name");
This will produce the following output −
[ "Chris", "David", "Bob" ]
- Related Articles
- Get distinct record values in MongoDB?
- MongoDB query to get distinct FirstName values from documents
- Get Distinct Values with Sorted Data in MongoDB?
- MongoDB query to get only distinct values
- Getting distinct values from object array in MongoDB?
- How to get max values for distinct elements in MongoDB
- Get distinct first word from a string with MongoDB?
- Get the length of distinct values in an array with MongoDB
- Get the maximum count of distinct values in a separate column with MySQL
- How to get distinct list of sub-document field values in MongoDB?
- How to get distinct values for non-key column fields in Laravel?
- Python Pandas - Get unique values from a column
- Get distinct first words in a string with MongoDB?
- Select distinct values from three columns and display in a single column with MySQL
- Get distinct levels of array field in MongoDB?

Advertisements