[英]MongoDB multiple joins with sub documents
我有两个 collections,
{
"userId": 1,
"name": 'John',
"profile": 'john.png'
},
{
"userId": 2,
"name": 'Doe',
"profile": 'doe.png'
},
{
"userId": 3,
"name": 'John Doe',
"profile": 'johndoe.png'
}
{
"postId": 1,
"userId": 1,
"postContent": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
"comments": [
{
"comment": "sample comment",
"commentedBy": 2,
},
{
"comment": "Another sample comment",
"commentedBy": 3,
}
],
}
如何通过 mongoose 中的单个查询获取帖子详细信息,包括单个帖子的用户详细信息和个人评论的用户详细信息?
您可能想要使用 Mongoose 提供的“填充”方法: https://mongoosejs.com/docs/populate.html
它允许您在架构定义中“链接”您的 collections,并在单个查询中查询和填充所有相关的 collections,例如
Posts.findOne({ postId: 1 }).populate('user')
按照上面的文档链接了解有关如何编写模式的更多详细信息。
您可以使用$aggregate
和$lookup
来执行此类
db.posts.aggregate(
[
{
$lookup:
{
from: "users",
localField: "userId",
foreignField: "userId",
as: "users"
}
}
]
).pretty()
这将打印如下
{
"_id" : ObjectId("5ecceb468d4390391825b79d"),
"postId" : 1,
"userId" : 1,
"postContent" : "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
"comments" : [
{
"comment" : "sample comment",
"commentedBy" : 2
},
{
"comment" : "Another sample comment",
"commentedBy" : 3
}
],
"users" : [
{
"_id" : ObjectId("5ecceb168d4390391825b79a"),
"userId" : 1,
"name" : "John",
"profile" : "john.png"
}
]
}
参考来自 MongoDB
https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.