Tutorialspoint

1 Answer
Anvi Jain

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" ]

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.