Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query mongo in php?

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?

This is the mongo document

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?

like image 407
michael Avatar asked Mar 17 '11 04:03

michael


People also ask

Can I use MongoDB with PHP?

You can add the driver to your application to work with MongoDB in PHP. The MongoDB PHP Driver consists of the two following components: The extension , which provides a low-level API and mainly serves to integrate libmongoc and libbson with PHP.

Can you query in MongoDB?

MongoDB queries provide the simplicity in process of fetching data from the database, it's similar to SQL queries in SQL Database language. While performing a query operation, one can also use criteria or conditions which can be used to retrieve specific data from the database.

How do I search for a string in MongoDB?

Use the $text query operator to perform text searches on a collection with a text index. $text will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.


1 Answers

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.

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')));

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

like image 97
svjson Avatar answered Sep 30 '22 06:09

svjson