mongodb - 更新 MongoDB 中的递归文档
问题描述
我的一个 MongoDB 集合中有一个递归结构,如下所示:
{
"id": String,
"date": Date,
"text": String
"replies": [{
// Same structure as above
}]
}
我需要通过添加对嵌套文档的回复来更新此层次结构中的文档。保证如下:
- 要回复的对象保证存在。
- 要发布回复的对象的路径是已知的(即,我们有一系列
_id
要导航的属性)。 - 递归深度没有限制。
搜索 SO 给我以下相关问题:
基于后者,我的尝试是:
await commCollection.update(
{ _id: topLevel['_id'] },
{
$push: {
'replies.$[].$[comment_arr].replies': {
id: commentId,
text: comment,
date,
replies: []
}
}
},
{ arrayFilters: [{ 'comment_arr.id': responseTo }]}
);
其中topLevel
是根文档,responseTo
是id
要添加回复的对象的属性。然而,这似乎不起作用。我做错了什么,我该如何做到这一点?
更新:下面的一个例子。这是来自 MongoDB Atlas 的文档示例:
{
"_id": {
"$oid": "605fdb8d933c5f50b4d2225e"
},
"id": "mr9pwc",
"username": "recrimination-logistical",
"upvotes": {
"$numberInt": "0"
},
"downvotes": {
"$numberInt": "0"
},
"text": "Top-level comment",
"date": {
"$date": {
"$numberLong": "1616894861300"
}
},
"replies": [{
"id": "dflu1h",
"username": "patrolman-hurt",
"upvotes": {
"$numberInt": "0"
},
"downvotes": {
"$numberInt": "0"
},
"text": "Testing reply level 1!",
"date": {
"$date": {
"$numberLong": "1618387567042"
}
},
"replies": [] // ----> want to add a reply here
}]
}
我已经指出我们希望在哪里添加回复。responseTo
在这种情况下是dflu1h
.
解决方案
- 只需要删除
$[]
位置 - arrayFilters 中的字段名称必须是以小写字母开头的字母数字字符串,
comment_arr
仅更改为任何字母,例如commentArr
,删除特殊字符
await commCollection.update(
{ _id: topLevel['_id'] },
{
$push: {
"replies.$[commentArr].replies": {
id: commentId,
text: comment,
date,
replies: []
}
}
},
{ arrayFilters: [{ "commentArr.id": responseTo }] }
)
推荐阅读
- javascript - React JS 渲染错误的列表和键
- google-cloud-platform - 限制 gsutil -m 线程
- json - 如何编辑 JSON 结构
- c# - MvcOptions.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes 到底发生了什么变化?
- c# - 正确理解异步/等待。它是如何正确的?
- c# - Xamarin,使用 x:name 找不到另一个按钮
- python - 如何找到列表中第二个元素的最小值
- xslt - 删除与 XSLT 中的数字连接的额外零
- docker - 检测容器内的 docker socket 是属于运行在其中的 docker daemon 还是从容器主机注入的
- javascript - 如何使用 CLI 命令 html2react 将 html 转换为 react 组件?