downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

MongoCollection::findOne> <MongoCollection::ensureIndex
[edit] Last updated: Fri, 18 Sep 2009

view this page in

MongoCollection::find

(PECL mongo >=0.9.0)

MongoCollection::findQuerys this collection

Описание

public MongoCursor MongoCollection::find ([ array $query = array() [, array $fields = array() ]] )

Параметри

query

The fields for which to search.

fields

Fields of the results to return.

Връщани стойности

Returns a cursor for the search results.

Примери

Example #1 MongoCollection::find() example

This example demonstrates how to search for a range.

<?php

// search for documents where 5 < x < 20
$rangeQuery = array('x' => array( '$gt' => 5'$lt' => 20 ));

$cursor $collection->find($rangeQuery);

?>


add a note add a note User Contributed Notes MongoCollection::find
Andrew Rose (blog.andrewrose.co.uk) 20-Sep-2011 07:48
An undocumented feature is that you can pass a stdClass instead of an array to $fields which will allow you to get around the issue of PHP casting string values to integers which mongo doesn't like.  i.e.

array('123' => 0, '321' => 0);

becomes:

array(213 => 0, 312 => 0);

which will trip up with the error:

PHP Fatal error:  Uncaught exception 'MongoException' with message 'field names must be strings'

The fix is as simple as:

<?php
$fields
= new stdClass;
$fields->{123} = 0;
$fields->{321} = 0;
?>
nospam at alexyves dot fr 09-Dec-2010 06:28
This will work with versions >=1.5.3, please note that this is just a example of the way to use the or statement.

<?php
  $connection
= new Mongo();

 
$db = $connection->test;
 
$collection = $db->test;
 
// Clean the DB before the test.
 
$collection->drop();
 
$collection = $db->test;

 
$apple = array(
   
'fruit' => 'Apple',
   
'type' => 'Juice',
  );

 
$orange = array(
   
'fruit' => 'Orange',
   
'type' => 'Marmalade',
  );

 
$collection->insert($apple);
 
$collection->insert($orange);

 
// Basic find
 
$results = $collection->find(array('fruit' => 'Apple'));

  foreach(
$results as $result)
  {
    echo
sprintf("Fruit: %s, Type: %s%s", $result['fruit'], $result['type'], PHP_EOL);
  }
?>

Output:

Fruit: Apple, Type: Juice

Now an advanced search with "or" statement.

<?php
 
// Advanced find with "OR" note the double array.
  // if you use double quotes escape the or "\$or"
 
$results = $collection->find( array( '$or' => array( array('fruit' => 'Apple'), array('fruit' => 'Orange') ) ) );

  foreach(
$results as $result)
  {
    echo
sprintf("Fruit: %s, Type: %s%s", $result['fruit'], $result['type'], PHP_EOL);
  }
?>

Output:

Fruit: Apple, Type: Juice
Fruit: Orange, Type: Marmalade

 
show source | credits | stats | sitemap | contact | advertising | mirror sites