php 如何在php中查询mongo?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5334723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:03:01  来源:igfitidea点击:

How to query mongo in php?

phpmongodbmongodb-php

提问by michael

So I've got this simple login function that is trying to match email address with a password in the database and compare it with the user entered data via form.

所以我有这个简单的登录功能,它试图将电子邮件地址与数据库中的密码进行匹配,并将其与用户通过表单输入的数据进行比较。

function login($email, $password){
    $m = new Mongo("localhost"); 
    $m->connect();
    $db = $m->users;
    $collection = $db->test_collection;

    echo "<pre>";
    var_dump($collection->findOne(array('name' => 'john'))); //returns correctly
    var_dump($collection->find(array('name' => 'john'))); //returns mongo cursor object
    echo "</pre>";
}

I don't understand why the find() only returns a cursor object. Answers?

我不明白为什么 find() 只返回一个游标对象。答案?

This is the mongo document

这是mongo文档

array(5) {
  ["_id"]=>
  object(MongoId)#22 (1) {
    ["$id"]=>"4d7eaa848baf84d32b000000"
  }
  ["activated"]=> (true)
  ["email"]=> "[email protected]"
  ["name"]=> "john"
  ["password"]=> "334c4a4c42fdb79d7ebc3e73b517e6f8"
}

How would I do a "WHERE" query that would find both email and password in the same document? I'm obviously not getting the paramaters correct for the find() and findOne() queries. What is the correct syntax in PHP?

我将如何执行“WHERE”查询以在同一文档中同时找到电子邮件和密码?对于 find() 和 findOne() 查询,我显然没有得到正确的参数。PHP 中的正确语法是什么?

采纳答案by svjson

findis supposed to return a cursor - you can read more about them here: http://www.mongodb.org/display/DOCS/Queries+and+Cursors. To get the documents from the cursor, you will have to iterate over it.

find应该返回一个游标 - 你可以在这里阅读更多关于它们的信息:http: //www.mongodb.org/display/DOCS/Queries+and+Cursors。要从游标中获取文档,您必须对其进行迭代。

In your case, findOneis probably what you are after since you don't expect multiple users with the same username and password. The findOne function always returns at most one document, so there is no need for a cursor.

在您的情况下,findOne可能是您所追求的,因为您不希望多个用户使用相同的用户名和密码。findOne 函数始终最多返回一个文档,因此不需要游标。

To have multiple predicates in your queries, just add more fields to your query array:

要在查询中包含多个谓词,只需向查询数组中添加更多字段:

var_dump($collection->findOne(array('name' => 'john', 'password' => '334c4a4c42fdb79d7ebc3e73b517e6f8')));

(If that is correct PHP - my PHP is a bit rusty)

(如果这是正确的 PHP - 我的 PHP 有点生疏)

回答by Osin Toumani

try

尝试

return count($collection->find(array('name' => $name, 'password' => $password)));