- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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" ]
- Related Articles
- Get distinct first words in a string with MongoDB?
- Get distinct values from a column in MongoDB?
- Get Distinct Values with Sorted Data in MongoDB?
- MongoDB query to get distinct FirstName values from documents
- Find the first maximum length even word from a string in C++
- Get distinct pair of objects with all subdocuments in MongoDB?
- Get distinct record values in MongoDB?
- Get the length of distinct values in an array with MongoDB
- MongoDB query to get only distinct values
- Get distinct levels of array field in MongoDB?
- Find the first repeated word in a string in Python?
- Find the first repeated word in a string in Java
- Find the first repeated word in a string in C++
- Get first three letters from every string in C#
- MySQL query to extract first word from a field?

Advertisements