- Trending Categories
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
Using regex in MongoDB findOne()
The findOne() returns one document that satisfies the specified query criteria on the collection. Let us create a collection with documents −
> db.demo655.insertOne({subject:"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea050254deddd72997713cc") } > db.demo655.insertOne({subject:"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea0502b4deddd72997713cd") } > db.demo655.insertOne({subject:"Java"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea050314deddd72997713ce") }
Display all documents from a collection with the help of find() method −
> db.demo655.find();
This will produce the following output −
{ "_id" : ObjectId("5ea050254deddd72997713cc"), "subject" : "MySQL" } { "_id" : ObjectId("5ea0502b4deddd72997713cd"), "subject" : "MongoDB" } { "_id" : ObjectId("5ea050314deddd72997713ce"), "subject" : "Java" }
Following is the query to use regex in findOne() −
> db.demo655.findOne({subject:{$regex:/M/}});
This will produce the following output −
{ "_id" : ObjectId("5ea050254deddd72997713cc"), "subject" : "MySQL" }
Advertisements