

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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" ]
- Related Questions & Answers
- Get distinct first word from a string with MongoDB?
- Get Distinct Values with Sorted Data in MongoDB?
- Get distinct record values in MongoDB?
- Get distinct values from a column in MongoDB?
- Get distinct pair of objects with all subdocuments in MongoDB?
- Interchanging first letters of words in a string in JavaScript
- 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?
- MongoDB query to get distinct FirstName values from documents
- How to get max values for distinct elements in MongoDB
- Print first n distinct permutations of string using itertools in Python
- Count distinct value in MongoDB?
- Can I get the first item in a Cursor object in MongoDB?
- Longest string with two distinct characters in JavaScript
Advertisements