【发布时间】:2021-07-18 04:44:26
【问题描述】:
我的一个 MongoDB 集合中有一个递归结构,如下所示:
{
"id": String,
"date": Date,
"text": String
"replies": [{
// Same structure as above
}]
}
我需要通过添加对嵌套文档的回复来更新此层次结构中的文档。保证如下:
- 要回复到的对象保证存在。
- 要发布回复的对象的路径是已知的(即,我们有一系列
_id属性可供导航)。 - 递归深度没有限制。
搜索 SO 给我以下相关问题:
- Querying, 2013 - 建议切换到图形数据库。
-
Updating, 2015 - 建议使用
$[]运算符。
基于后者,我的尝试是:
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。
【问题讨论】:
标签: mongodb