MongoDB equivalent of `select distinct(name) from collectionName where age = “25”`?


You can use distinct() to get the equivalent of select distinct. Let us first create a collection with documents −

> db.distinctNameAndAgeDemo.insertOne({"ClientFirstName":"John","Age":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd12759e3526dbddbbfb60b")
}
> db.distinctNameAndAgeDemo.insertOne({"ClientFirstName":"Larry","Age":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd12768e3526dbddbbfb60c")
}
> db.distinctNameAndAgeDemo.insertOne({"ClientFirstName":"David","Age":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd12773e3526dbddbbfb60d")
}
> db.distinctNameAndAgeDemo.insertOne({"ClientFirstName":"Carol","Age":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd1277ee3526dbddbbfb60e")
}
> db.distinctNameAndAgeDemo.insertOne({"ClientFirstName":"Sam","Age":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd12793e3526dbddbbfb60f")
}
> db.distinctNameAndAgeDemo.insertOne({"ClientFirstName":"Larry","Age":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd127a3e3526dbddbbfb610")
}
> db.distinctNameAndAgeDemo.insertOne({"ClientFirstName":"Carol","Age":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd127aae3526dbddbbfb611")
}

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5cd12759e3526dbddbbfb60b"),
   "ClientFirstName" : "John",
   "Age" : 23
}
{
   "_id" : ObjectId("5cd12768e3526dbddbbfb60c"),
   "ClientFirstName" : "Larry",
   "Age" : 25
}
{
   "_id" : ObjectId("5cd12773e3526dbddbbfb60d"),
   "ClientFirstName" : "David",
   "Age" : 25
}
{
   "_id" : ObjectId("5cd1277ee3526dbddbbfb60e"),
   "ClientFirstName" : "Carol",
   "Age" : 26
}
{
   "_id" : ObjectId("5cd12793e3526dbddbbfb60f"),
   "ClientFirstName" : "Sam",
   "Age" : 25
}
{
   "_id" : ObjectId("5cd127a3e3526dbddbbfb610"),
   "ClientFirstName" : "Larry",
   "Age" : 25
}
{
   "_id" : ObjectId("5cd127aae3526dbddbbfb611"),
   "ClientFirstName" : "Carol",
   "Age" : 26
}

Following query is the equivalent of `select distinct(name) from collectionName where age = “25” −

> db.distinctNameAndAgeDemo.distinct("ClientFirstName", {"Age": 25});

This will produce the following output −

[ "Larry", "David", "Sam" ]

Above, we have displayed those client’s name whose age is 25.

Updated on: 30-Jul-2019

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements