To get only a single result, use findOne() and fetch on the basis of id. Let us create a collection with documents −
> db.demo340.insertOne({_id:1,"Name":"Chris",Age:21}); { "acknowledged" : true, "insertedId" : 1 } > db.demo340.insertOne({_id:2,"Name":"David",Age:23}); { "acknowledged" : true, "insertedId" : 2 } > db.demo340.insertOne({_id:3,"Name":"Bob",Age:20}); { "acknowledged" : true, "insertedId" : 3 } > db.demo340.insertOne({_id:4,"Name":"Sam",Age:19}); { "acknowledged" : true, "insertedId" : 4 }
Display all documents from a collection with the help of find() method −
> db.demo340.find();
This will produce the following output −
{ "_id" : 1, "Name" : "Chris", "Age" : 21 } { "_id" : 2, "Name" : "David", "Age" : 23 } { "_id" : 3, "Name" : "Bob", "Age" : 20 } { "_id" : 4, "Name" : "Sam", "Age" : 19 }
Here is the query to findby id −
> db.demo340.findOne({_id:1});
This will produce the following output −
{ "_id" : 1, "Name" : "Chris", "Age" : 21 }