Difference between find() and findOne() methods in MongoDB?

MongoDBDatabaseBig Data Analytics

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
raja
Published on 30-Apr-2019 12:28:12
Advertisements