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" }