mongodb java findone,MongoDB中的find()和findOne()方法显示不同的结果

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" : "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

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

解决方案

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

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

find() - nomatter 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 :

tsX4u.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值