【发布时间】:2018-12-25 21:18:31
【问题描述】:
大家好,我是 MongoDB 新手,正在寻找答案
-
有什么方法可以在不循环的情况下更新嵌套数组。
foreach ($post->comments as $key => $comment) { if ($comment['posted_by'] == $authUser['id']) { $data = $post->update([ "comments.$key.description" => $dataArray['description'], "comments.$key.updated_at" => $dataArray['updated_at'], ]); }}
我想做如下的事情。
$post = Post::where('_id', $id)->where('comments.*.id', $commentId)->update(array('description' => $desc));
或者我必须为此编写原始 MongoDB 查询。 我在主 cmets 下也有 1 级嵌套评论,所以如果我想更新嵌套评论,我必须循环评论数组而不是嵌套评论数组。
if ($subCommentId) {
foreach ($comment as $nestedkey => $nestedComments) {
if ($nestedComments['id'] === $subCommentId && $nestedComments['posted_by'] == $authUser['id']) {
$data = $post->update([
"comments.$key.$nestedkey.description" => $dataArray['description'],
"comments.$key.$nestedkey.updated_at" => $dataArray['updated_at'],
]);
}
}
}
类似这样的:
$post = Post::where('_id', $id)->where('comments.*.id', $commentId)->where('comments.*.*.id', $subCommentId)->update(array('description' => $desc));
- 将注释作为数组存储在同一个集合中是否很好,或者我应该为此创建一个新集合,因为最大 BSON 文档大小为 16 兆字节,它可以存储多少 cmets,例如 10K 或更多?
以下是我在一个 Collection 下的示例评论数组格式。
"comments" : [
{
"description" : "description some",
"channel" : "swachhata-citizen-android",
"user_role" : "Citizen",
"id" : "5b4dc367d282f",
"user_role_id" : ObjectId("5accd7f8309a203be03b6441"),
"created_at" : "2018-07-17 15:52:31",
"updated_at" : "2018-07-17 15:52:31",
"ip_address" : "127.0.0.1",
"user_agent" : "PostmanRuntime/6.4.1",
"deleted" : false,
"channel_id" : "5acccfe4309a2038347a5c47",
"posted_by" : NumberInt(1),
"comments" : [
{
"description" : "some description nested",
"channel" : "swachhata-citizen-android",
"user_role" : "Citizen",
"id" : "5b4dcfc7022db",
"user_role_id" : ObjectId("5accd7f8309a203be03b6441"),
"created_at" : "2018-07-17 16:45:19",
"updated_at" : "2018-07-17 16:45:19",
"ip_address" : "127.0.0.1",
"user_agent" : "PostmanRuntime/6.4.1",
"deleted" : false,
"channel_id" : "5acccfe4309a2038347a5c47",
"posted_by" : NumberInt(1)
}
]
}
]
谢谢。 :)
【问题讨论】:
-
嗨@Prafful Panwar,你有什么解决办法吗...
-
@rbvishnu 不,我是通过 foreach $data = $post->update([ "cmets.$key.cmets.$nestedkey.description" => $dataArray['description'] , "cmets.$key.cmets.$nestedkey.updated_at" => $dataArray['updated_at'], ]);
-
你试过我的答案@Prafful Panwar 吗?
标签: mongodb laravel laravel-5.5 jenssegers-mongodb