Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" ]
Advertisements