如何在php中查询mongo? [英] How to query mongo in php?

查看:85
本文介绍了如何在php中查询mongo?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>";
}

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

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

这是mongo文档

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

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

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?

推荐答案

find应该返回游标-您可以在此处阅读有关游标的更多信息:

find is 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.

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

In your case, findOne is 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.

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

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

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

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

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

这篇关于如何在php中查询mongo?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆