How to write empty associative array ({}) in MongoDB from PHP

When I try to insert an empty associative array ( hashmap

/ dictionary

/ dict

/ {}

) into MongoDB from PHP, it is always inserted as a non-associative empty array ( list

/ []

). Can I force an associative array?

Example:

$m = new Mongo('mongodb://localhost:27017');
$db = $m->selectDB('test');
$collection = $db->selectCollection('test');

// 1: inserts []
$d = array( 'x' => array() );
$collection->insert($d);

// 2: inserts []
$d = array( 'y' => array('a'=>'123') );
unset($d['y']['a']);
$collection->insert($d);

// 3: inserts {}
$d = array( 'z' => array('a'=>'123') );
$collection->insert($d);
$collection->update(array('_id' => $d['_id']), array('$unset' => array('z.a'=>true)));

      

And the results:

> db.test.find().pretty()
{ "_id" : ObjectId("510fb9ede695c5381a000000"), "x" : [ ] }
{ "_id" : ObjectId("510fb9ede695c5381a000001"), "y" : [ ] }
{ "_id" : ObjectId("510fb9ede695c5381a000002"), "z" : { } }

      

The third way does what I want, but it's a little awkward and requires two requests. Is there a better solution?

+3


source to share


2 answers


Are you storing an empty object or an array, what's the difference? In BSON, arrays and objects are stored in the same way as dict . Anyway, to your question.

For PHP MongoDB driver, an empty array is just an empty array, so it stores it as an array. When you add a key / value pair to an array, the way the driver understands is to store an object.



If you really want to keep an empty object try:

$d = new \stdClass();
$collection->insert(array('z' => $d));

      

+5


source


There is actually a difference in that it will be considered non-associative [] if empty, and then will not allow the associative key to be set by throwing an exception:

MongoCursorException: can't append to array using string field name

      

You should use as an object as such:



$d = array( 'x' => (object) array() );
$collection->insert($d);

      

https://jira.mongodb.org/browse/PHP-172

+1


source







All Articles