[英]PHP/MongoDB $set use for update an array in a collection
我正在尝试对集合中的特定单个数组进行update(),但是虽然可以在单个特定数组上使用$ push参数正常运行,但不能与$ set参数一起使用。
我不太了解其背后的逻辑,因为当我使用$ pushing元素的示例时:
$post_comment = array('$push' =>
array("comments" => array(
"_id" => new MongoId(),
"comment" => htmlspecialchars($_POST['comment']),
"author" => $user->username,
"date" => new MongoDate()
)
)
);
$entries->update(array(
"_id" => $_GET["id"]), $post_comment);
它为我提供了一个在MongoDB数据库中的数组,它看起来或多或少像这样(分别插入了四个项目):
{
"_id" : "css-clearfix-explained",
"comments" : [
{
"_id" : ObjectId("540cc940af105b19133c9869"),
"comment" : "aaa",
"author" : "maciejsitko",
"date" : ISODate("2014-09-07T21:08:16.215Z")
},
{
"_id" : ObjectId("540cc943af105b19133c986a"),
"comment" : "bbb",
"author" : "maciejsitko",
"date" : ISODate("2014-09-07T21:08:19.542Z")
},
{
"_id" : ObjectId("540cc946af105b19133c986b"),
"comment" : "ccc",
"author" : "maciejsitko",
"date" : ISODate("2014-09-07T21:08:22.968Z")
}
]
}
从本质上讲,这是我想要的,并且根据文档,在逻辑上可以正常工作。 但是,当我尝试使用$ set尝试编辑单个注释时,采用类似的方式,如下所示:
$edit_comment = array('$set' =>
array("comments" => array(
"_id" => new MongoId($_POST['cmt-id']),
"comment" => htmlspecialchars($_POST['edit-comment']),
"author" => $user->username,
"date" => new MongoDate()
)
)
);
$entries->update(array(
"_id" => $_GET["id"]), $edit_comment);
它输出四个不同的数组代替以前的数组,以说明这一点,我将展示将第一个注释“ aaa”更新为“ ddd”时发生的情况:
{
"_id" : "css-clearfix-explained",
"comments" : {
"_id" : ObjectId("540cc940af105b19133c9869"),
"comment" : "ddd\r\n ",
"author" : "maciejsitko",
"date" : ISODate("2014-09-07T21:12:10.833Z")
}
}
几乎删除了所有四个数组元素,并在它们的位置出现了四个独立的数组元素四个字段。
怎么会? 它不应该像上面$ push的示例一样工作吗?
您未在comments
指定索引。 因此,$ set用提供的关联数组替换了数组comments
。 如果要更新注释,请在第一个参数中更改查询以通过唯一字段匹配注释。 例如,日期。 在第二个参数中,使用位置$运算符。
例:
$edit_comment = array('$set' =>
array("comments.$" => array(
"_id" => new MongoId($_POST['cmt-id']),
"comment" => htmlspecialchars($_POST['edit-comment']),
"author" => $user->username,
"date" => new MongoDate()
)
)
);
// this assumes the post date is unique. On second though use something else.
$query = array( "_id" => $_GET["id"], "comments.date" => $_POST['post-date'])
$entries->update( $query, $edit_comment);
签出更多信息和更好的解释: MongoDB-$ set更新或推送Array元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.