Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I have a Mongo database wherein the users collection I have just 1 document. I do a find() and a findOne() operations using the username filter. I get what I think is an incorrect result from find() operation.

MongoDB shell version: 3.2.10 

connecting to: test 

Server has startup warnings: 

2016-10-20T20:37:32.681-0700 I CONTROL [initandlisten] 2016-10-20T20:37:32.681-0700 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. 

2016-10-20T20:37:32.681-0700 I CONTROL [initandlisten] ** We suggest setting it to 'never' 

2016-10-20T20:37:32.681-0700 I CONTROL [initandlisten] 2016-10-20T20:37:32.681-0700 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. 2016-10-20T20:37:32.681-0700 I CONTROL [initandlisten] ** We suggest setting it to 'never' 

2016-10-20T20:37:32.681-0700 I CONTROL [initandlisten] 

> use lab2 switched to db lab2 

> db.users.find() 

"_id" : ObjectId("5807ac0765f24dd0660e4332"), 

"username" : "avtrulzz", 

"fname" : "Abc", 

"lname" : "Def", 

"email" : "[email protected]", 

"password" : "rootuser", 

"mobile" : NumberLong(1234567890) 

> db.users.findOne() { 

"_id" : ObjectId("5807ac0765f24dd0660e4332"), 

"username" : "avtrulzz", 

"fname" : "Abc", 

"lname" : "Def", 

"email" : "[email protected]", 

"password" : "rootuser", 

"mobile" : NumberLong(1234567890) 

> if (db.users.find({username : "noSuchUsername"})) { 

... print ("Username exists"); 

... } else { 

... print ("User does not exist"); } 

Username exists 

> if (db.users.findOne({username : "noSuchUsername"})) { print ("Username exists"); } else { print ("User does not exist"); } User does not exist 

> if (db.users.findOne({username : "avtrulzz"})) { print ("Username exists"); } else { print ("User does not exist"); } Username exists

2 Answers

0 votes
by (106k points)

To understand the difference between these three you should understand the basic difference between findOne() and find():

  • findOne() - if query matches, the first document is returned, otherwise null.

  • find() - no matter number of documents matched, a cursor is returned, never null.

So when put in an if condition, findOne() can convert to false when it doesn't match any document. As find returns a cursor object and never returns null, will convert to true when put in an if condition.

find and findOne() return the following for empty collection :

enter image description here

0 votes
by (107k points)
  1. findOne() returns a document, or nil/null.

  2. find() returns a cursor, which can be empty. But the object returned is always defined.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...