Difference Between find and findOne Methods in MongoDB



The findOne() returns first document if query matches otherwise returns null. The find() method does not return null, it returns a cursor.

Let us implement the concept of find() and findOne() and create a collection with documents −

> db.createCollection('emptyCollection');
{ "ok" : 1 }

Let us count how many documents are in the above collection −

> db.emptyCollection.count();

This will produce the following output −

0

There is no document present in the above collection.

Following is the query to check the result with findOne() −

> if(db.emptyCollection.findOne()){print("Returns Cursor")} else {print("Not returning cursor")}

This will produce the following output −

Not returning cursor

Following is the query to check the result with find() −

> if(db.emptyCollection.find()){print("Returns Cursor")} else {print("Not returning cursor")}

This will produce the following output −

Returns Cursor
Updated on: 2019-07-30T22:30:25+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements