MongoCollection::find
(PECL mongo >=0.9.0)
MongoCollection::find — Queries this collection, returning a MongoCursor for the result set
Description
Parameters
-
query
-
The fields for which to search. MongoDB's query language is quite extensive. The PHP driver will in almost all cases pass the query straight through to the server, so reading the MongoDB core docs on » find is a good idea.
WarningPlease make sure that for all special query operators (starting with $) you use single quotes so that PHP doesn't try to replace "$exists" with the value of the variable $exists.
-
fields
-
Fields of the results to return. The array is in the format array('fieldname' => true, 'fieldname2' => true). The _id field is always returned.
Return Values
Returns a cursor for the search results.
Examples
Example #1 MongoCollection::find() example
This example demonstrates basic search options.
<?php
$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'produce');
// search for fruits
$fruitQuery = array('Type' => 'Fruit');
$cursor = $collection->find($fruitQuery);
foreach ($cursor as $doc) {
var_dump($doc);
}
// search for produce that is sweet. Taste is a child of Details.
$sweetQuery = array('Details.Taste' => 'Sweet');
echo "Sweet\n";
$cursor = $collection->find($sweetQuery);
foreach ($cursor as $doc) {
var_dump($doc);
}
?>
The above example will output:
array(4) { ["_id"]=> object(MongoId)#7 (1) { ["$id"]=> string(24) "50a87dd084f045a19b220dd6" } ["Name"]=> string(5) "Apple" ["Type"]=> string(5) "Fruit" ["Details"]=> array(2) { ["Taste"]=> string(5) "Sweet" ["Colour"]=> string(3) "Red" } } array(4) { ["_id"]=> object(MongoId)#8 (1) { ["$id"]=> string(24) "50a87de084f045a19b220dd7" } ["Name"]=> string(5) "Lemon" ["Type"]=> string(5) "Fruit" ["Details"]=> array(2) { ["Taste"]=> string(4) "Sour" ["Colour"]=> string(5) "Green" } } Sweet: array(4) { ["_id"]=> object(MongoId)#7 (1) { ["$id"]=> string(24) "50a87dd084f045a19b220dd6" } ["Name"]=> string(5) "Apple" ["Type"]=> string(5) "Fruit" ["Details"]=> array(2) { ["Taste"]=> string(5) "Sweet" ["Colour"]=> string(3) "Red" } }
See MongoCursor for more information how to work with cursors.
Example #2 MongoCollection::find() example
This example demonstrates how to search for a range.
<?php
$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');
// search for documents where 5 < x < 20
$rangeQuery = array('x' => array( '$gt' => 5, '$lt' => 20 ));
$cursor = $collection->find($rangeQuery);
foreach ($cursor as $doc) {
var_dump($doc);
}
?>
The above example will output:
array(2) { ["_id"]=> object(MongoId)#10 (1) { ["$id"]=> string(24) "4ebc3e3710b89f2349000000" } ["x"]=> int(12) } array(2) { ["_id"]=> object(MongoId)#11 (1) { ["$id"]=> string(24) "4ebc3e3710b89f2349000001" } ["x"]=> int(12) }
See MongoCursor for more information how to work with cursors.
Example #3 MongoCollection::find() example using $where
This example demonstrates how to search a collection using javascript code to reduce the resultset.
<?php
$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');
$js = "function() {
return this.name == 'Joe' || this.age == 50;
}";
$cursor = $collection->find(array('$where' => $js));
foreach ($cursor as $doc) {
var_dump($doc);
}
?>
The above example will output:
array(3) { ["_id"]=> object(MongoId)#7 (1) { ["$id"]=> string(24) "4ebc3e3710b89f2349000002" } ["name"]=> string(3) "Joe" ["age"]=> int(20) }
Example #4 MongoCollection::find() example using $in
This example demonstrates how to search a collection using the $in operator.
<?php
$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');
$cursor = $collection->find(array(
'name' => array('$in' => array('Joe', 'Wendy'))
));
?>
The above example will output:
array(3) { ["_id"]=> object(MongoId)#7 (1) { ["$id"]=> string(24) "4ebc3e3710b89f2349000002" } ["name"]=> string(3) "Joe" ["age"]=> int(20) }
Example #5 Getting results as an array
This returns a MongoCursor. Often, when people are starting out, they are more comfortable using an array. To turn a cursor into an array, use the iterator_to_array() function.
<?php
$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');
$cursor = $collection->find();
$array = iterator_to_array($cursor);
?>
The above example will output:
array(3) { ["4ebc40af10b89f5149000000"]=> array(2) { ["_id"]=> object(MongoId)#6 (1) { ["$id"]=> string(24) "4ebc40af10b89f5149000000" } ["x"]=> int(12) } ["4ebc40af10b89f5149000001"]=> array(2) { ["_id"]=> object(MongoId)#11 (1) { ["$id"]=> string(24) "4ebc40af10b89f5149000001" } ["x"]=> int(12) } ["4ebc40af10b89f5149000002"]=> array(3) { ["_id"]=> object(MongoId)#12 (1) { ["$id"]=> string(24) "4ebc40af10b89f5149000002" } ["name"]=> string(3) "Joe" ["age"]=> int(20) } }
Using iterator_to_array() forces the driver to load all of the results into memory, so do not do this for result sets that are larger than memory!
Also, certain system collections do not have an _id
field. If you are dealing with a collection that might have documents
without _ids, pass FALSE
as the second argument to
iterator_to_array() (so that it will not try to use the
non-existent _id values as keys).
See Also
- MongoCollection::findOne() - Queries this collection, returning a single element
- MongoCollection::insert() - Inserts a document into the collection
- MongoDB core docs on » find.
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с базами данных
- Расширения для работы с базами данных отдельных производителей
- MongoDB
- Базовые классы
- Функция MongoCollection::aggregate() - Perform an aggregation using the aggregation framework
- Функция MongoCollection::aggregateCursor() - Execute an aggregation pipeline command and retrieve results through a cursor
- Функция MongoCollection::batchInsert() - Inserts multiple documents into this collection
- Функция MongoCollection::__construct() - Creates a new collection
- Функция MongoCollection::count() - Counts the number of documents in this collection
- Функция MongoCollection::createDBRef() - Creates a database reference
- Функция MongoCollection::createIndex() - Creates an index on the specified field(s) if it does not already exist.
- Функция MongoCollection::deleteIndex() - Deletes an index from this collection
- Функция MongoCollection::deleteIndexes() - Delete all indices for this collection
- Функция MongoCollection::distinct() - Retrieve a list of distinct values for the given key across a collection.
- Функция MongoCollection::drop() - Drops this collection
- Функция MongoCollection::ensureIndex() - Creates an index on the specified field(s) if it does not already exist.
- MongoCollection::find
- Функция MongoCollection::findAndModify() - Update a document and return it
- Функция MongoCollection::findOne() - Queries this collection, returning a single element
- Функция MongoCollection::__get() - Gets a collection
- Функция MongoCollection::getDBRef() - Fetches the document pointed to by a database reference
- Функция MongoCollection::getIndexInfo() - Returns information about indexes on this collection
- Функция MongoCollection::getName() - Returns this collection's name
- Функция MongoCollection::getReadPreference() - Get the read preference for this collection
- Функция MongoCollection::getSlaveOkay() - Get slaveOkay setting for this collection
- Функция MongoCollection::getWriteConcern() - Get the write concern for this collection
- Функция MongoCollection::group() - Performs an operation similar to SQL's GROUP BY command
- Функция MongoCollection::insert() - Inserts a document into the collection
- Функция MongoCollection::parallelCollectionScan() - Returns an array of cursors to iterator over a full collection in parallel
- Функция MongoCollection::remove() - Remove records from this collection
- Функция MongoCollection::save() - Saves a document to this collection
- Функция MongoCollection::setReadPreference() - Set the read preference for this collection
- Функция MongoCollection::setSlaveOkay() - Change slaveOkay setting for this collection
- Функция MongoCollection::setWriteConcern() - Set the write concern for this database
- Функция MongoCollection::toIndexString() - Converts keys specifying an index to its identifying string
- Функция MongoCollection::__toString() - String representation of this collection
- Функция MongoCollection::update() - Update records based on a given criteria
- Функция MongoCollection::validate() - Validates this collection
Коментарии
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
For the fields parameter, the documentaion says: "The _id field is always returned".
Knowing that mongodb allows you to uncheck the _id field ("the _id field is the only field that you can explicitly exclude"; source: http://docs.mongodb.org/manual/reference/method/db.collection.find/#db.collection.find), I tried it with php and it works : you can exclude the _id field.
Example : the following fields parameter will exclude the field "_id"
$fields = array('timestamp' => true, 'rank' => true, '_id' => false);
<?php
$m = new MongoClient();
$db = $m->selectDB('school');
$collection = new MongoCollection($db, 'student');
//Find where class=5
$where=array('class'=>5);
$cursor = $collection->find($where);
//Find where class !=5
$where=array('class' => array('$ne'=>5));
$cursor = $collection->find($where);
//Find where age >20
$where=array('age' => array('$gt'=>20));
$cursor = $collection->find($where);
//Find where age >=20
$where=array('age' => array('$gte'=>20));
$cursor = $collection->find($where);
//Find where age <20
$where=array('age' => array('$le'=>20));
$cursor = $collection->find($where);
//Find where age <=20
$where=array('age' => array('$lte'=>20));
$cursor = $collection->find($where);
//Finc where class=10 or marks=80
$where=array( '$or' => array( array(' class' =>10), array('marks'=>80) ) );
$cursor = $collection->find($where);
//Finc where class=12 AND marks=70
$where=array( '$and' => array( array(' class' =>12), array('marks'=>70) ) );
$cursor = $collection->find($where);
?>
As the docs specify, '$or' conditions (and similar) get passed right on to MongoDB directly. It appears that to make a simple "field, $or, field" compound query work, all parts must be wrapped as a gigantic $and.
Here's how I got a find(), findOne(), and findAndModify() to obey such a compound $or for matching on fields, one of which is represented in data as either a string or integer:
<?php
$query =
array('$and' =>
array(
array('assessment_id' => $doc->assessment_id),
array('$or' =>
array(
array('participant_id' => $doc->participant_id),
array('participant_id' => (string)$doc->participant_id),
),
),
array('measure_id' => $doc->measure_id)
),
);
$thedoc = $collection->findOne($query);
return $thedoc;
?>
example of sort and find
$client = new MongoDB\Client("mongodb://localhost:27017");
$product = $client->db->product;
$filter = [];
$options = ['sort' => ['catid' => 1], 'limit' => 10];
$list = $product->find($filter, $options);