Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-26718

find() v/s findOne() search on a single record

    • Type: Icon: Question Question
    • Resolution: Done
    • Priority: Icon: Minor - P4 Minor - P4
    • None
    • Affects Version/s: 3.2.10
    • Component/s: JavaScript, Querying
    • Labels:
      None

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

      See the find operation is returning user exists which is not true. findOne() is behaving correctly.

      > use lab2
      switched to db lab2
      > db.users.find()
      { "_id" : ObjectId("5807ac0765f24dd0660e4332"), "username" : "avtrulzz", "fname" : "Abc", "lname" : "Def", "email" : "test@yahoo.co.in", "password" : "rootuser", "mobile" : NumberLong(1234567890) }
      > db.users.findOne()
      {
      	"_id" : ObjectId("5807ac0765f24dd0660e4332"),
      	"username" : "avtrulzz",
      	"fname" : "Abc",
      	"lname" : "Def",
      	"email" : "test@yahoo.co.in",
      	"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
      > 
      

            Assignee:
            david.storch@mongodb.com David Storch
            Reporter:
            avtrulzz Anuvrat Tiku
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:
              Resolved: