Calling with PHP Variables in MongoDB
Join the DZone community and get the full member experience.
Join For FreeSo I’ve been doing a lot of work, for work, in MongoDB lately and I’ve learned an awful lot. Or, depending on your point of view, a lot that’s just awful.
See, there’s not what you could even charitably call a lot of MongoDB documentation to begin with. If you filter what is available on, oh, say, PHP implementation, well the results just dwindle to something roughly the same size as a tax-collector’s heart.
Here’s the scenario — I’ve been working on adding a mongo abstraction class on top of my base-data abstraction class — whereas said classes are extended by the table-level class instantiation. This allows me to keep all of my query logic in the middle tier of the class design, generic and administrative functions in the base class, and table-specific stuff in the table class. So far, so good, right?
Well, I get the mongo constructor running and, like it’s mySQL counterpart, I have an rule in every table constructor that states “if I pass a indexed field and it’s value to the constructor, then instantiate the class pre-populated with that record.”
And that’s where things start to head south.
In my constructor logic, I’m only allowing single-value key->value pairs as constructor parameters with the design intention of getting a record from the db using the pkey of the table/collection. In other words, you get one column and one column value. So, if you’re going to instantiate a new user object, you’d probably want to pass-in the primary-key field of a user and that field’s value:
$objUser = new UserProfile(‘email’, ‘mshallop@gmail.com’); // instantiate a new user object with this email address
Still pretty easy. I bang out the mySQL equivalent in nothing flat. I hit a huge pothole when I get to the mongo side.
The method is defined as a protected abstract method in the base class – so this method has to appear in both child classes as defined in the parent:
protected abstract function loadClassById($_key, $_value);
So I have my methods defined in both the mySQL and mongoDB middle layer. My strategy for the mongo fetch-and-return is pretty simple — once the class has been instantiated, do the following:
- make sure the $_key value exists in the allowed field list
- make sure the $_value has a value
- query mongodb using .findOne()
- store the return key->value pairs in the member array
- return status
That’s pretty much it. But I run into huge problems when I get to step 3 — use the mongoDB findOne command.
The
findOne method takes an array input of the key->value pair. From
the mongo command line, you’d execute something like this:
> db.session_ses.findOne({'idpro_ses' : 1}) { "_id" : ObjectId("4ea1af93ddc69802376b56d1"), "id_ses" : 1, "idpro_ses" : 1 }
( Just to show you that the data exists in the mongo collection…)
But, the PHP-ized version of the method is a wee bit different:
$this->collection->findOne(array(‘idpro_ses’ => 1));
All of the examples that I’ve been able to locate show using the method by invoking it using literals. My problem is that I have the two input parameters sent to the method ($_key and $_value) and I’ve got to find a way to get the PHP version of the method call to work using variables instead of constants. This is what didn’t work:
$this->collection->findOne(array($_key => $_value));
$this->collection->findOne(array(“‘” . $_key . “‘” => $_value));
$this->collection->findOne(array(“{$_key}” => $_value));
$aryData = array();
$aryData[$_key] = $_value;
$this->collection->findOne($aryData);
or
$this->collection->findOne(var_dump($aryData));
I thought this worked but I was wrong:
$this->collection->findOne(array(array_keys($aryData) => array_values($aryData)));
This format returned a mongo record —
the problem was that it returned the first mongo record independently of
any key-search criteria.
What finally worked for me was this:
$qs = array(); // QueryStructure switch($this->fieldTypes[$_k]) { case 'int' : $_v = intval($_v); break; case 'str' : $_v = strval($_v); break; case 'float' : $_v = floatval($_v); break; } $qs[$_k] = $_v; $aryData = $this->collection->findOne($qs);
[Update]
I encountered a
similar problem when trying to update records in a mongo collection —
while I could update the record from the mongo command line, I did not
experience the same success in trying to execute the command from within
my PHP program…
$foo = $collection->find(array(‘id_geo’ => $row['id_geo']));
Consistently failed. No exceptions were caught, and mongo’s findLastError() reported no errors in the transaction.
After several iterations of debugging and attempting various work-arounds, I stumbled upon the solution as being one of casting.
While the variable was being evaluated in the PHP array as type int,
somehow this wasn’t being interpreted that way by Mongo. Casting the
variable to an integer:
$foo = $collection->find(array(‘id_geo’ => intval($row['id_geo'])));
generated a successful query for both the find() and my update() functions.
As I gain experience with Mongo, I expect to discover more of these little mannerisms…
Source: http://shallop.com/2011/10/mongodb-findone-calling-with-php-variables-not-literals/
Opinions expressed by DZone contributors are their own.
Trending
-
What to Pay Attention to as Automation Upends the Developer Experience
-
A Data-Driven Approach to Application Modernization
-
Designing a New Framework for Ephemeral Resources
-
Micro Frontends on Monorepo With Remote State Management
Comments