Get distinct first word from a string with MongoDB?


To get distinct first word from a string, you can use distinct(). Let us first create a collection with documents −

> db.distinctFirstWordDemo.insertOne(
   {
      "_id": 100,
      "StudentName":"John",
      "StudentFeature": "John is a good player",
      "Subject":"MongoDB"
   }
);
{ "acknowledged" : true, "insertedId" : 100 }
> db.distinctFirstWordDemo.insertOne(
   {
      "_id": 101,
      "StudentName":"Carol",
      "StudentFeature": "Carol is not a good player",
      "Subject":"MongoDB"
   }
);
{ "acknowledged" : true, "insertedId" : 101 }

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

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

This will produce the following output −

{
   "_id" : 100,
   "StudentName" : "John",
   "StudentFeature" : "John is a good player",
   "Subject" : "MongoDB"
}
{
   "_id" : 101,
   "StudentName" : "Carol",
   "StudentFeature" : "Carol is not a good player",
   "Subject" : "MongoDB"
}

Following is the query to get distinct first word from a string −

> student = db.distinctFirstWordDemo.distinct("StudentFeature", {"Subject" : "MongoDB"}).map(function(st){
   return st.split(" ")[0];
});
[ "John", "Carol" ]
> printjson(student);

This will produce the following output −

[ "John", "Carol" ]

Updated on: 30-Jul-2019

113 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements