Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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" ]
Advertisements
