Retrieving the first document in a MongoDB collection?



To retrieve the first document in a collection, you can use findOne(). Following is the syntax

var anyVariableName=db.yourCollectionName.findOne(); //To print result at MongoDB console write the variable name yourVariableName

Let us first create a collection with documents

> db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Robert","ClientAge":23}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ca2325966324ffac2a7dc6d") } > db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Chris","ClientAge":26}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ca2326266324ffac2a7dc6e") } > db.retrieveFirstDocumentDemo.insertOne({"ClientName":"Larry","ClientAge":29}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ca2326a66324ffac2a7dc6f") } > db.retrieveFirstDocumentDemo.insertOne({"ClientName":"David","ClientAge":39}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ca2327566324ffac2a7dc70") }

Following is the query to display all documents from a collection with the help of find() method

> db.retrieveFirstDocumentDemo.find().pretty();

This will produce the following output

{    "_id" : ObjectId("5ca2325966324ffac2a7dc6d"),    "ClientName" : "Robert",    "ClientAge" : 23 } {    "_id" : ObjectId("5ca2326266324ffac2a7dc6e"),    "ClientName" : "Chris",    "ClientAge" : 26 } {    "_id" : ObjectId("5ca2326a66324ffac2a7dc6f"),    "ClientName" : "Larry",    "ClientAge" : 29 } {    "_id" : ObjectId("5ca2327566324ffac2a7dc70"),    "ClientName" : "David",    "ClientAge" : 39 }

Following is the query to retrieve first document in a collection

> var firstDocumentOnly=db.retrieveFirstDocumentDemo.findOne(); > firstDocumentOnly;

This will produce the following output

{    "_id" : ObjectId("5ca2325966324ffac2a7dc6d"),    "ClientName" : "Robert",    "ClientAge" : 23 }
Updated on: 2019-07-30T22:30:25+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements