note 111913 deleted from mongocollection.save by aharvey
| From: | aharvey@php.net | Date: | Thu, 11 Apr 2013 06:01:49 +0000 |
| Subject: | note 111913 deleted from mongocollection.save by aharvey | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-194448@lists.php.net to get a copy of this message | ||
Note Submitter: Daniel Ribbens
----
I noticed that when my object included an array that I didn't want to write to MongoDB as an
associated array, I had to use json_encode and json_decode to get the desired results. Example:
<?php
$m = new Mongo(MONGOSERVER);
$db = $m->testdb;
$collection = $db->test;
$object = new testobj();
$collection->save($object);
class testobj {
var $foo;
var $tags;
var $associated;
function __construct() {
$this->foo = 'bar';
// no keys for tags array
$this->tags =
json_encode(array('simple','dimple','thimble'));
// keys for associated array
$this->associated = array('simple','dimple','thimble');
}
}
?>
Result stored in MongoDB:
[_id] => MongoId Object (
[$id] => 5165d41019c2f59614000000
)
[foo] => bar
[tags] => ["simple","dimple","thimble"]
[associated] => Array (
[0] => simple
[1] => dimple
[2] => thimble
)
Then when retrieving, json_decode() on the tags is useful if you want to do a foreach() across the
tags array. There may be a more elegant solution, but this was the best I could come up with!