- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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 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" ]
Advertisements