本文介绍了MongoDB中的find()和findOne()方法显示不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Mongo数据库,在用户集合中我只有1个文档.我使用用户名过滤器执行find()findOne()操作.我从find()操作中得到了我认为是不正确的结果.

I have a Mongo database where in 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

请参阅find()操作正在返回用户,这是不正确的. findOne()的行为正确.

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

推荐答案

首先,findOne()find()之间的基本区别:

First of all, basic difference between findOne() and find():

  • findOne() -如果查询匹配,则返回第一个文档,否则返回null.

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

find() -符合条件的文档数量,返回游标,绝不为null.

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

因此,当置于if条件时,findOne()在与任何文档都不匹配时可以转换为false.当find返回一个游标对象并且从不返回null时,将其置于if条件下将转换为true.

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.

findfindOne()返回以下内容以获取空集合:

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

这篇关于MongoDB中的find()和findOne()方法显示不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 02:16