Get distinct first words in a string with MongoDB?


To get distinct first words in a string, use split(). Let us first create a collection with documents −

> db.demo129.insertOne({"Words":"This is the MySQL","CountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e305d6368e7f832db1a7f6b")
}
> db.demo129.insertOne({"Words":"MongoDB is NOSQL database","CountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e305d7b68e7f832db1a7f6c")
}

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

> db.demo129.find();

This will produce the following output −

{ "_id" : ObjectId("5e305d6368e7f832db1a7f6b"), "Words" : "This is the MySQL", "CountryName" : "US" }
{ "_id" : ObjectId("5e305d7b68e7f832db1a7f6c"), "Words" : "MongoDB is NOSQL database", "CountryName" : "US" }

Following is the query to get distinct first words in a string −

> w = db.demo129.distinct("Words", {"CountryName" : "US"}).map(function(doc){ return doc.split(" ")[0]; });
[ "This", "MongoDB" ]

Now you can display with the help of printjson().

> printjson(w);

This will produce the following output −

[ "This", "MongoDB" ]

Updated on: 31-Mar-2020

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements