mongodb 使用 PHP 更新文档中的嵌套数组
文档结构示例是:
{
"dob": "12-13-2001",
"name": "Kam",
"visits": {
"0": {
"service_date": "12-5-2011",
"payment": "40",
"chk_number": "1234455",
},
"1": {
"service_date": "12-15-2011",
"payment": "45",
"chk_number": "3461234",
},
"2": {
"service_date": "12-25-2011",
"payment": "25",
"chk_number": "9821234",
}
}
}
我尝试使用以下命令仅更新访问 - 2 中的“付款”和访问 - 1 中的 chk_number :
$query_criteria = array("name" => "Kam", "dob" => "12-13-2001");
$updated_data = array();
$updated_data['visits'][1]['chk_number'] = 567;
$updated_data['visits'][2]['payment'] = 100;
$ret = $collection->update( $query_criteria, array('$set' => $updated_data), array("safe" => true) );
但此更新会删除所有访问,并用仅包含付款和 chk_number 的访问覆盖它们。
我是 mongodb 和 PHP 的新手。谁能指出我做错了什么以及如何解决这个问题。
非常感谢提前......
document structure example is:
{
"dob": "12-13-2001",
"name": "Kam",
"visits": {
"0": {
"service_date": "12-5-2011",
"payment": "40",
"chk_number": "1234455",
},
"1": {
"service_date": "12-15-2011",
"payment": "45",
"chk_number": "3461234",
},
"2": {
"service_date": "12-25-2011",
"payment": "25",
"chk_number": "9821234",
}
}
}
i am trying to update only "payment" in visit - 2 and chk_number in visit - 1 using following:
$query_criteria = array("name" => "Kam", "dob" => "12-13-2001");
$updated_data = array();
$updated_data['visits'][1]['chk_number'] = 567;
$updated_data['visits'][2]['payment'] = 100;
$ret = $collection->update( $query_criteria, array('$set' => $updated_data), array("safe" => true) );
But this update deletes all the visits and overwrite them with vists containing only payment and chk_number .
I am new to mongodb and PHP. Can anyone please point me towards what wrong am i doing and how to fix this problem.
Many thanks in advance........
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用点表示法。
你正在做的是这样的:
它基本上意味着“找到一个文档并用这个新文档覆盖它”。
我编写的代码是用 Javascript 编写的(因为它们会出现在 mongo shell 中)。我让您自行翻译为正确的 PHP(我不是 PHP 专家)。
You should use a dot notation.
What you're doing is this:
And it basically means "find a document and overwrite it with this new one".
The code I wrote are in Javascript (as they would appear in mongo shell). I leave it up to you to translate to proper PHP (I'm not a PHP guy).