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")];
Related
So I have the following code to get a document from a collection in my database:
$manager = new MongoDB\Driver\Manager('mongodb+srv://<username>:<password>#cluster0.hyqa4.mongodb.net/academic?retryWrites=true&w=majority');
$filter = ['username' => $uname];
$options = ['projection' => ['_id' => 0]];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery("academic.users", $query);
foreach($cursor as $document) {
print_r($document);
}
I'm able to successfully retrieve a document by searching for the username, so if $uname is "Jon", I get the following output:
stdClass Object ( [username] => Jon [email] => Jon#mail.com [passwd] => pass123 )
However, what I want to do is just return a single value from the document, so if I wanted to get the value for email, it would return:
Jon#mail.com
...so then I could store that value as a variable.
How would I do this?
Std class objects can be accessed via -> operator. So you can user $document->email to access individual email. Is this what you are looking for
$manager = new MongoDB\Driver\Manager('mongodb+srv://<username>:<password>#cluster0.hyqa4.mongodb.net/academic?retryWrites=true&w=majority');
$filter = ['username' => $uname];
$options = ['projection' => ['_id' => 0]];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery("academic.users", $query);
foreach($cursor as $document) {
print_r($document->email);
}
I have written following lines of code in php like below
$keyarguments = array($orlastname,$oradmissionno,$orcourse,$orgender,$ordob,$orrollno,$ormiddlename,$oremail,$orguardian,$orphone,$orfullname,$orfirstmiddle,$orfirstlast);
foreach ($keyarguments as $key) {
${$key} = array('$or' => array(array("dummy_feild" => new MongoRegex("/$empty/i"))));
}
I want that code should be executed like
orlastname = array('$or' => array(array("dummy_feild" => new MongoRegex("/$empty/i"))));
oradmissionno = array('$or' => array(array("dummy_feild" => new MongoRegex("/$empty/i"))));
...
...
...
and so on
Please help!!!
try this, use string as the $keyarguments's elemnt.
$keyarguments = array('orlastname', 'oradmissionno');
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);
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
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);
}