Mongodb with php can't use where query - php

I have been install Mongodb v.2.6.7 with php mongo driver v.1.6.3
When I get data all it work normally but if I use where query It return empty array back to me.

<?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);
}
source

Related

sorting mongo regex query in php

I have a mongo collection and I'd like to obtain all the document whose names start with a given letter on PHP. My code:
$letter = "c";
$client = new MongoDB\Client();
$pme = $client->selectCollection("belgium", "pme");
$regex = new MongoDB\BSON\Regex ("^$letter", "i");
$query = array('name' => $regex); // 1
$query = array('name' => $regex, array( 'sort' => array( 'OrderBy' => 1 ) )); // 2
$query = new MongoDB\Driver\Query( array('name' => $regex), array( 'sort' => array( 'OrderBy' => 1 ) ) ); // 3
$cursor = $pme->find($query);
Whe I use query 1. I got all documents starting with letter c but not ordered. When I use query 2, I got nothing. And finally when I use query 3 I get almost every document, not just those starting with with 'c'. What I am doing wrong here?
In mongo method sort should be applied on cursor obtained by find:
$letter = "c";
$client = new MongoDB\Client();
$pme = $client->selectCollection("belgium", "pme");
$regex = new MongoDB\BSON\Regex ("^$letter", "i");
$query = array('name' => $regex);
// sort by field `name` happens here
$options = array("sort" => array("name" => 1), );
$cursor = $pme->find($query, $options);

Using Regex in new MongoDB library for PHP7/HHVM

Trying to figure out how to use Regex in new MongoDB library
I didn't find real world example of usage MongoDB\BSON\Regex so I come up with the code below:
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['word' => ['word' => 'heelo']]);
$bulk->insert(['word' => ['word' => 'hello']]);
$manager->executeBulkWrite('db.collection', $bulk);
$filter = ['word' => ['word' => new MongoDB\BSON\Regex("hello","i")]];
$query = new MongoDB\Driver\Query($filter);
$cursor = $manager->executeQuery('db.collection', $query);
foreach ($cursor as $document) {
var_dump($document);
}
But it shows nothing. Does anyone know how to use it?
I've found the answer. I should write query like:
$filter = ['word.word' => new MongoDB\BSON\Regex("hello","i")];

Mongodb $nin php Not Working

This shows me everything (including 55d9d86746ba9a3a7f642b83).
I don't want it to show me the data in the array $veri.
$veri=Array
(
[0] => 55d9d86746ba9a3a7f642b83
)
$urun = $c->find(array('_id' => array('$nin' => $veri)));
Try the below code:
<?php
$mongo = new Mongo();
$db = $mongo->selectDB("foo");
$cur = $db->bar;
$veri = array(
new MongoId('55d9d86746ba9a3a7f642b83')
);
$urun = $cur->find(array('_id' => array('$nin' => $veri)));
foreach($urun as $doc) {
var_dump($doc);
}
?>
Notice how I use MongoId, instead of just copy pasting the id as is. Also notice that the array doesn't need an index [0]

Elastica PHP Query Where Or

How to make a WHERE categoryId = 1 OR categoryId = 2 query with Elastica ? I'm doing this but I got 0 result :
$query = new \Elastica\Query();
$boolOr = new \Elastica\Filter\BoolOr();
$boolOr->addFilter(new \Elastica\Filter\Term(array('categoryId' => '1')));
$boolOr->addFilter(new \Elastica\Filter\Term(array('categoryId' => '2')));
$filtered = new \Elastica\Query\Filtered(new \Elastica\Query\MatchAll(), $boolOr);
$query->setQuery($filtered);
$products = $type->search($query)->getResults();
Here is a working example:
$index = $this->_createIndex();
$type = $index->getType('test');
$doc1 = new Document('', array('categoryId' => 1));
$doc2 = new Document('', array('categoryId' => 2));
$doc3 = new Document('', array('categoryId' => 3));
$type->addDocument($doc1);
$type->addDocument($doc2);
$type->addDocument($doc3);
$index->refresh();
$boolOr = new \Elastica\Filter\BoolOr();
$boolOr->addFilter(new \Elastica\Filter\Term(array('categoryId' => '1')));
$boolOr->addFilter(new \Elastica\Filter\Term(array('categoryId' => '2')));
$resultSet = $type->search($boolOr);
You don't need to use the filtered and matchall query. The working example can be found here: https://github.com/ruflin/Elastica/pull/887/files

Retrieve fields of Mongo collection in PHP

I tried using the fields() method on the cursor:
<?php
$mongo = new Mongo("mongodb://localhost");
print_r($mongo);
$db = $mongo->test;
// access collection
$collection = $db->test;
// execute query
// retrieve all documents
print_r($test);
$cursor = $collection->find();
print_r($cursor);
$fields = $cursor->fields(array("summary" => true));
print_r($fields);
The output is:
Mongo Object ( [connected] => 1 [status] => [server:protected] => [persistent:protected] => )
MongoCursor Object ( )
MongoCursor Object ( )
Looks like the driver and the connection work but I can't retrieve the distinct summarization of the fields.
Assume that we have access to mongodb database with the name db, are going to retrieve data from MyCollection and use MongoDB\Driver\Manager:
$manager = new MongoDB\Driver\Manager( $DB_CONNECTION_STRING );
Then we retrieve data in this case by name with a limit 2 documents and want to get only fields name, age and address among many others. Projection option can be used to specify which fields should be returned using 0 to exclude and 1 to include:
$filter = ['name' => 'John'];
$options = [ 'projection' => ['_id' => 0, 'name' => 1, 'age' => 1, 'address' => 1], 'limit' => 2 ];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
If we need to get all columns, then we simply omit projection option at all as the following:
$filter = ['name' => 'daniel'];
$options = [];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
const HOST = 'localhost';
const PORT = 27017;
const DBNAME = 'test';
const COLLECTION = 'test';
$connectionString = sprintf('mongodb://%s:%d', HOST, PORT);
try {
$connection = new Mongo($connectionString);
$database = $connection->selectDB(DBNAME);
} catch (MongoConnectionException $e) {
throw $e;
}
$collection = $database->selectCollection(COLLECTION);
try{
$query = array();
$specifyKey = array("summary" => true);
$cursor = $collection->find($query , $specifyKey);
}catch(MongoException $e) {
die('Failed to find One data '.$e->getMessage());
}catch (MongoCursorException $e) {
echo "error message: ".$e->getMessage()."\n";
echo "error code: ".$e->getCode()."\n";
}
while ($cursor->hasNext()){
$nextCursor = $cursor->getNext();
//process next cursor
}
After the $cursor variable try an foreach instead. It goes through the cursor results.
foreach($cursor as $document) {
var_dump($document);
}

Categories