我是 MongoDB 和 Lithium 的新手,我真的找不到处理嵌套文档的“好方法”。我注意到当我尝试时
$user = Users::find('first' ... );
$user->somenewfield = array('key' => 'val');
我为“somenewfield”得到的是一个文档对象。但是还有一个 DocumentArray 类——它们之间有什么区别?
当我打电话
$user->save();
在 Mongo 中的结果(如预期的那样):
"somenewfield" : {
"key": "value"
}
好的,但是当我稍后想向数组添加一个新的键值并尝试时
$user->somenewfield['newkey'] = 'newval';
var_dump($user->somenewfield->to('array')); // shows the old and the new key-value pairs
$user->save(); // does not work - the new pair is not added
使用锂向文档添加新数组的正确方法是什么?更新数组/向数组添加新值的正确方法是什么?我应该给数组值一个键吗?
提前感谢您的帮助。我有点卡住了......阅读文档,阅读代码......但在某些时候很难单独找出所有内容:)
编辑: 最后我发现我使用嵌套数组的方式是 $push 和 $pull:
Users::update(array('$push' => array('games' => (string) $game->_id)),
array(
'_id' => $this->user()->_id,
'games' => array('$ne' => (string) $game->_id)),
array('atomic' => false));
最佳答案
我觉得处理子文档有些怪癖,你可以试试:
$somenewfield = $user->somenewfield;
$somenewfield->newkey = newvalue;
$user->somenewfield = $somenewfield;
$user->save();
或者替代语法:
$user->{'somenewfield.newkey'} = $newvalue;
$user->save();
您应该能够在测试中找到更多示例(在文档的任何测试中查看测试/数据)。
关于mongodb - 在 Lithium 和 MongoDB 中使用嵌套文档/数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11569208/