Get distinct values from a column in MongoDB?

MongoDBDatabaseBig Data Analytics

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" ]
raja
Published on 31-Mar-2020 11:47:52
Advertisements