Retrieve only a single document specifying a criteria in MongoDB?


Use findOne() in MongoDB for this. The findOne() returns one document that satisfies the specified query criteria on the collection.

Let us create a collection with documents −

> db.demo596.insertOne({_id:1,"FirstName":"John","LastName":"Smith"});
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo596.insertOne({_id:2,"FirstName":"John","LastName":"Doe"});
{ "acknowledged" : true, "insertedId" : 2 }
> db.demo596.insertOne({_id:3,"FirstName":"Chris","LastName":"Brown"});
{ "acknowledged" : true, "insertedId" : 3 }
> db.demo596.insertOne({_id:4,"FirstName":"David","LastName":"Miller"});
{ "acknowledged" : true, "insertedId" : 4 }

Display all documents from a collection with the help of find() method −

> db.demo596.find();

This will produce the following output −

{ "_id" : 1, "FirstName" : "John", "LastName" : "Smith" }
{ "_id" : 2, "FirstName" : "John", "LastName" : "Doe" }
{ "_id" : 3, "FirstName" : "Chris", "LastName" : "Brown" }
{ "_id" : 4, "FirstName" : "David", "LastName" : "Miller" }

Here is the query to retrieve only a single document −

> db.demo596.findOne({"FirstName":"John"});

This will produce the following output −

{ "_id" : 1, "FirstName" : "John", "LastName" : "Smith" }

Updated on: 15-May-2020

323 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements