Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Get distinct first word from a string with MongoDB?
To get distinct first words from a string field in MongoDB, use the distinct() method combined with JavaScript's map() and split() functions to extract and return the first word from each string.
Syntax
db.collection.distinct("fieldName", query).map(function(str) {
return str.split(" ")[0];
});
Sample Data
db.distinctFirstWordDemo.insertMany([
{
"_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"
}
]);
{
"acknowledged": true,
"insertedIds": {
"0": 100,
"1": 101
}
}
Display All Documents
db.distinctFirstWordDemo.find();
{
"_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"
}
Example: Extract Distinct First Words
student = db.distinctFirstWordDemo.distinct("StudentFeature", {"Subject": "MongoDB"}).map(function(st) {
return st.split(" ")[0];
});
printjson(student);
[ "John", "Carol" ]
How It Works
-
distinct("StudentFeature", {"Subject": "MongoDB"})gets all unique values from the StudentFeature field where Subject is "MongoDB" -
map()applies a function to each string in the result array -
split(" ")[0]splits each string by spaces and returns the first element (index 0)
Conclusion
Use MongoDB's distinct() method with JavaScript's map() and split() functions to efficiently extract distinct first words from string fields. This approach combines MongoDB's query capabilities with client-side string processing.
Advertisements
