Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Get the top most document from a MongoDB collection
To get the topmost document, use find() along with limit(). To fetch only a single document, consider using limit(1). Let us create a collection with documents −
> db.demo681.insertOne({_id:101,Name:"Chris"});
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo681.insertOne({_id:102,Name:"Bob"});
{ "acknowledged" : true, "insertedId" : 102 }
> db.demo681.insertOne({_id:103,Name:"David"});
{ "acknowledged" : true, "insertedId" : 103 }
> db.demo681.insertOne({_id:104,Name:"Bob"});
{ "acknowledged" : true, "insertedId" : 104 }
> db.demo681.insertOne({_id:105,Name:"Sam"});
{ "acknowledged" : true, "insertedId" : 105 }
Display all documents from a collection with the help of find() method −
> db.demo681.find();
This will produce the following output −
{ "_id" : 101, "Name" : "Chris" }
{ "_id" : 102, "Name" : "Bob" }
{ "_id" : 103, "Name" : "David" }
{ "_id" : 104, "Name" : "Bob" }
{ "_id" : 105, "Name" : "Sam" }
Following is the query to get the topmost element −
> db.demo681.find().limit(1);
This will produce the following output −
{ "_id" : 101, "Name" : "Chris" } Advertisements
