如何从PHP向MongoDB写空的关联数组({}) [英] How to write empty associative array ({}) to MongoDB from PHP
问题描述
当我尝试从PHP向MongoDB插入空的关联数组(hashmap
/dictionary
/dict
/{}
)时,它总是作为非关联的空数组插入(list
/[]
).我可以强制关联数组吗?
When I try to insert empty associative array (hashmap
/dictionary
/dict
/{}
) to MongoDB from PHP, it is always inserted as non-associative empty array (list
/[]
). Can I force associative array?
示例:
$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" : { } }
第三种方法可以满足我的要求,但是有点尴尬,需要两个查询.有更好的解决方案吗?
The third way does what I want, but it is a bit awkward and requires two queries. Is there a better solution?
推荐答案
无论您存储的是空对象还是数组,都有什么区别?在BSON中,数组和对象的存储方式与字典相同.无论如何,对您的问题.
Whether you store an empty object or array, what's the difference? In BSON, arrays and objects are stored the same way, as a dict. Anyways, to your question.
对于PHP MongoDB驱动程序,一个空数组就是一个空数组,因此将其存储为一个数组.当您将键/值对添加到数组时,驱动程序将其理解为它应该存储对象.
For the PHP MongoDB driver an empty array is just that, an empty array, so it stores it as an array. When you add a key/value pair to the array, that's how the driver understands it should store an object.
如果您真的想存储一个空对象,请尝试:
If you really want to store an empty object, try :
$d = new \stdClass();
$collection->insert(array('z' => $d));
这篇关于如何从PHP向MongoDB写空的关联数组({})的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!