MongoDB findOne不返回任何东西 [英] MongoDB findOne not returning anything
问题描述
根据PHP的mongo页面findOne,这应该工作正常,但它不是。
$ email = array 'email'=> $ _POST ['email'];
$ conn = new MongoClient(mongodb:// localhost:27017 /);
$ xyz = $ conn-> > users;
$ cursor = $ xyz-> findOne($ email);
print_r($ cursor);
当使用find方法而不是findOne时,这是工作。
$ email = array('email'=> $ _ POST ['email']);
$ pass = $ _POST ['password'];
$ conn = new MongoClient('localhost');
$ db = $ conn-> database;
$ collection = new MongoCollection($ db,'users');
$ cursor = $ collection-> find($ email);
foreach($ cursor as $ obj){
$ test = $ obj ['email'];
print_r($ test);}
解决方案p> findOne()不返回像find()这样的游标 - 请在这里检查文档:
http://www.php.net//manual/en/mongocollection.findone.php
此外,你的代码中似乎有一个语法错误,你在第一行缺少一个右括号。此外,使用名为$ cursor的变量,当它不返回光标往往是一个坏主意,因为它导致混乱的那些查看代码。最后,你在两个代码示例之间使用不同的方法 - 不同的变量名,不同的字符串传递给MongoClient(),一个使用对MongoCollection()的调用,一个
考虑到所有这一切,我会提出以下建议:
#Add right)
$ email = array('email'=> $ _POST ['email']) ;
$ conn = new MongoClient(mongodb:// localhost:27017 /);
$ db = $ conn-> database;
$ collection = new MongoCollection($ db,'users');
$ findoneResult = $ collection-> findOne($ email);
print_r($ findOneResult);
According to the PHP mongo page for findOne, this should be working fine but its not.
$email = array('email' => $_POST['email']; $conn = new MongoClient("mongodb://localhost:27017/"); $xyz = $conn->database->users; $cursor = $xyz->findOne($email); print_r ($cursor);
This is working when using the find method instead of findOne.
$email = array('email'=>$_POST['email']); $pass = $_POST['password']; $conn = new MongoClient( 'localhost' ); $db = $conn->database; $collection = new MongoCollection($db, 'users'); $cursor = $collection->find($email); foreach ($cursor as $obj){ $test = $obj['email']; print_r($test); }
Can someone explain why this is happening ?
解决方案findOne() does not return a cursor like find() does - please check the documentation here:
http://www.php.net//manual/en/mongocollection.findone.php
In addition you appear to have a syntax error in your code, you are missing a right parentheses in the first line. Also, using variables named "$cursor" when it's not returning a cursor tends to be a bad idea as it causes confusion for those viewing the code.
Finally, you are using different approaches between your two code samples - different variable names, different strings passed to MongoClient(), one uses a call to MongoCollection() and one does not, etc - very easy for problems to crop up in those differences.
Taking all that into account, I'd propose the following:
# Add right ) at end of following statement $email = array('email' => $_POST['email']); $conn = new MongoClient("mongodb://localhost:27017/"); $db = $conn->database; $collection = new MongoCollection($db, 'users'); $findoneResult = $collection->findOne($email); print_r ($findOneResult);
这篇关于MongoDB findOne不返回任何东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!