Working with MongoDB find()


The find() in MongoDB selects documents in a collection or view and returns a cursor to the selected documents.

The find() method with no parameters returns all documents from a collection and returns all fields for the documents. Let us see an example and create a collection with documents −

> db.demo405.insertOne({"StudentInfo":{"Name":"Chris"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e6f9134fac4d418a0178595")
}
> db.demo405.insertOne({"StudentInfo":{"Name":"David"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e6f9138fac4d418a0178596")
}
> db.demo405.insertOne({"StudentInfo":{"Name":"Bob"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e6f913cfac4d418a0178597")
}
> db.demo405.insertOne({"StudentInfo":{"Name":"John"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e6f9140fac4d418a0178598")
}

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

> db.demo405.find();

This will produce the following output −

{ "_id" : ObjectId("5e6f9134fac4d418a0178595"), "StudentInfo" : { "Name" : "Chris" } }
{ "_id" : ObjectId("5e6f9138fac4d418a0178596"), "StudentInfo" : { "Name" : "David" } }
{ "_id" : ObjectId("5e6f913cfac4d418a0178597"), "StudentInfo" : { "Name" : "Bob" } }
{ "_id" : ObjectId("5e6f9140fac4d418a0178598"), "StudentInfo" : { "Name" : "John" } }

Updated on: 03-Apr-2020

103 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements