我在 MongoDB 中有一个文档,我正在尝试解开它。我想展开带有comments
字段的文档,然后展开replies
每个评论中的字段。之后我需要将其倒回。
所以文档结构是这样的:
{
"_id": <some_id>,
"post_body": "test post",
"author_id": <some_user_id>,
"comments": [
{
"comment_body": "comment test",
"comment_author_id": <some_user_id>,
"replies": [
{
"reply_body": "reply test",
"reply_author_id": <some_user_id>
},
... more items
]
},
... more items
]
}
我还尝试使用附加的已保存 ID 从用户表中查找所有作者数据。
这是我现在的代码:
{
"$match": {"post_id": post_id}
},
{
"$lookup": {
"from": "usersLookup",
"localField": "author_id",
"foreignField": "_id",
"as": "author_data"
}
},
{
"$unwind": {
"path": "$comments",
"preserveNullAndEmptyArrays": True
}
},
{
"$lookup": {
"from": "usersLookup",
"localField": "comments.comment_author_id",
"foreignField": "_id",
"as": "comment_author_data"
}
},
{
"$unwind": {
"path": "$comments.replies",
"preserveNullAndEmptyArrays": True
}
},
{
"$lookup": {
"from": "usersLookup",
"localField": "comments.replies.reply_author_id",
"foreignField": "_id",
"as": "reply_author_data"
}
},
{
"$group": {
"_id": '$_id',
"post_body": {"$first": "$post_body"},
"author": {"$first": "$authorData"},
"comments": {
"$push": {
"comment_body": "$comments.comment_body",
"comment_author_data": "$comment_author_data",
"replies": {
"$push": {
"reply_body": "$comments.replies.reply_body",
"reply_author_data": "$reply_author_data"
}
}
}
}
}
}
我收到了这个错误
pymongo.errors.OperationFailure:不支持聚合项目运算符:'$push'
我想得到:
{
"_id": <some_id>,
"post_body": "test post",
"author_data": {"author_name": "test1"},
"comments": [
{
"comment_body": "comment test",
"comment_author_data": {"author_name": "test1"},
"replies": [
{
"reply_body": "reply test",
"reply_author_data": {"author_name": "test1"}
},
... more items
]
},
... more items
]
}
我需要在 MongoDB 查询中进行哪些更改?