当我尝试从 PHP 向 MongoDB 插入空关联数组 ( hashmap
/ dictionary
/ dict
/ {}
) 时,它总是作为非关联空数组 ( list
/ []
) 插入。我可以强制关联数组吗?
例子:
$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)));
结果:
> db.test.find().pretty()
{ "_id" : ObjectId("510fb9ede695c5381a000000"), "x" : [ ] }
{ "_id" : ObjectId("510fb9ede695c5381a000001"), "y" : [ ] }
{ "_id" : ObjectId("510fb9ede695c5381a000002"), "z" : { } }
第三种方式做我想要的,但有点尴尬,需要两个查询。有更好的解决方案吗?