MongoDB query to get distinct FirstName values from documents


For distinct values, use distinct(). Let us create a collection with documents −

> db.demo303.insertOne({FirstName:"Chris",LastName:"Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ea0f6f8647eb59e56202f")
}
> db.demo303.insertOne({FirstName:"John",LastName:"Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ea104f8647eb59e562030")
}
> db.demo303.insertOne({FirstName:"Chris",LastName:"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ea10df8647eb59e562031")
}
> db.demo303.insertOne({FirstName:"John",LastName:"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ea121f8647eb59e562032")
}
> db.demo303.insertOne({FirstName:"David",LastName:"Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ea136f8647eb59e562033")
}

Display all documents from a collection with the help of find() method −

> db.demo303.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e4ea0f6f8647eb59e56202f"),
   "FirstName" : "Chris",
   "LastName" : "Brown"
}
{
   "_id" : ObjectId("5e4ea104f8647eb59e562030"),
   "FirstName" : "John",
   "LastName" : "Doe"
}
{
   "_id" : ObjectId("5e4ea10df8647eb59e562031"),
   "FirstName" : "Chris",
   "LastName" : "Smith"
}
{
   "_id" : ObjectId("5e4ea121f8647eb59e562032"),
   "FirstName" : "John",
   "LastName" : "Smith"
}
{
   "_id" : ObjectId("5e4ea136f8647eb59e562033"),
   "FirstName" : "David",
   "LastName" : "Miller"
}

Following is the query to get the distinct FirstName values −

> db.demo303.distinct("FirstName");

This will produce the following output −

[ "Chris", "John", "David" ]

Updated on: 01-Apr-2020

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements