To find only a single document, use findOne() in MongoDB. Let us create a collection with documents −
> db.demo116.insertOne({"EmployeeId":101,"EmployeeName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2eff98d8f64a552dae635b") } > db.demo116.insertOne({"EmployeeId":102,"EmployeeName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2eff9fd8f64a552dae635c") } > db.demo116.insertOne({"EmployeeId":103,"EmployeeName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2effa5d8f64a552dae635d") } > db.demo116.insertOne({"EmployeeId":102,"EmployeeName":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5e2effb7d8f64a552dae635e") }
Display all documents from a collection with the help of find() method −
> db.demo116.find();
This will produce the following output −
{ "_id" : ObjectId("5e2eff98d8f64a552dae635b"), "EmployeeId" : 101, "EmployeeName" : "John" } { "_id" : ObjectId("5e2eff9fd8f64a552dae635c"), "EmployeeId" : 102, "EmployeeName" : "Bob" } { "_id" : ObjectId("5e2effa5d8f64a552dae635d"), "EmployeeId" : 103, "EmployeeName" : "David" } { "_id" : ObjectId("5e2effb7d8f64a552dae635e"), "EmployeeId" : 102, "EmployeeName" : "Mike" }
Following is the query to find only a single document in MongoDB −
> db.demo116.findOne({"EmployeeId":102});
This will produce the following output −
{ "_id" : ObjectId("5e2eff9fd8f64a552dae635c"), "EmployeeId" : 102, "EmployeeName" : "Bob" }