mongodb - 从 mongo 中的嵌入式文档中多次查找相同的集合
问题描述
我有一个帖子和评论的嵌入式文档。其中 comments 是包含用户详细信息的嵌入式文档commentedby
。用户名很可能经常更改。因此,每次访问评论时都需要查找 user 的值。
有没有一种有效的方法可以使用 mongo 查询来做到这一点。我不喜欢使用 unwind因为我会失去其他关于分组的帖子参数
{
"PostId":"Post001",
"Comments":[
{"_id": "001",
"CommentedBy":{
"_id":"User001",
"Name":"UserName001",
"email":"user001@eg.com"
}
},
{"_id": "002",
"CommentedBy":{
"_id":"User002",
"Name":"UserName002",
"email":"user001@eg.com"
}
},
{"_id": "003",
"CommentedBy":{
"_id":"User003",
"Name":"UserName003",
"email":"user001@eg.com"
}
}
]
}
用户文档不仅包含用户名和 ID。使用多次查找可能最终会引用User001
多次。
预期结果
{
"PostId":"Post001",
"Comments":[
{"_id": "001",
"CommentedBy":{
"_id":"User001",
"Name":"UserName001",
"email":"user001@eg.com",
"Group":"Marketing",
"Location":"India" }
},
{"_id": "002",
"CommentedBy":{
"_id":"User002",
"Name":"UserName002",
"email":"user002@eg.com",
"Group":"Engineering",
"Location":"USA"
}
},
{"_id": "003",
"CommentedBy":{
"_id":"User002",
"Name":"UserName002",
"email":"user002@eg.com",
"Group":"Engineering",
"Location":"USA"
}
}
]
}
UserDocument 看起来像这样
User = [
{
"_id":"User001",
"Name":"UserName001",
"email":"user001@eg.com",
"Group":"Marketing",
"Location":"USA"
},
{
"_id":"User002",
"Name":"UserName002",
"email":"user002@eg.com",
"Group":"Engineering",
"Location":"USA"
}
...
...
]
我试过的查询
db.getCollection('Posts').aggregate([
{$lookup:{
from: "User",
localField: "Comments.CommentedBy._id",
foreignField: "_id",
as: "Comments.CommentedBy"
}},
])
- 这对于带有 n 条评论的 n 条帖子是否有效
- mongo 在查找时会做某种优化,
User002
因为它需要查找两次。 - 如果 CommentedBy 是用户列表,在这种情况下如何进行 $lookup
解决方案
推荐阅读
- python - 循环遍历一个列表并创建数组,在一行中显示 n 的所有序列,然后是列表中的下一次迭代
- angular - 未捕获的错误:无法解析 UserService (?) 的所有参数
- c++ - 为什么我的 vector::erase 调用会抛出“vector subscript out of range”?
- ios - Swift iOS 应用程序 - 更改故事板 segue 类型的问题 - 无法从模态更改为显示
- django - 如何将 Django 日期时间转换为 HighCharts 格式
- javascript - 使用 javascript 下载 youtube 视频/音频流
- angular - 当用户仅通过输入查询来搜索选项时,matautocomplete 应该进行过滤
- flutter - 在屏幕中心对齐文本
- api - Http POST 在 Postman 中有效,但在 Flutter 中无效
- node.js - Node-Postgres SequelizeConnectionError:用户的密码验证失败