我在Mongo DB中有3个模型。
User
Posts - Linked to userid
Comments - Linked to userid
我需要获取以下几列作为最终结果。
Username | UserEmail | TotalPostsbyUser | TotalCommentsbyUser
现在要实现此目的,我正在使用多个异步循环。无论如何,我可以在单个查询中获取所需的结果吗?类似于MySQL中的联接吗?
答案 0 :(得分:0)
使用应使用Aggregation 但这可能不是执行此操作的最佳方法。 如果您需要多次查询,则应将这些号码缓存在其他地方。
db.users.aggregate([
{
$match: {
username: "USERNAME" // or any other condition here
}
},
{
$lookup: {
from: "posts",
let: { "userId": "$_id" },
pipeline: [
{ $match: { $expr: { $eq: ["$owner", "$$userId"] }}},
{ $project: {_id: 1}} ] // I assume that the foreign key is "owner"
as: "posts"
}
},
{
$lookup: {
from: "comments",
let: { "userId": "$_id" },
pipeline: [
{ $match: { $expr: { $eq: ["$owner", "$$userId"] }}},
{ $project: {_id: 1}} ] // I assume that the foreign key is "owner"
as: "comments"
}
},
{
$project: {
Username: "$username",
UserEmail: "$userEmail",
TotalPostsbyUser: { $size: "$posts"},
TotalCommentsbyUser: { $size: "$comments" }
}
}])
答案 1 :(得分:0)
除了在项目阶段进行计数之外,您无需加入集合,而只需在查找阶段进行计数,否则不适用于大型数据集:
db.users.aggregate([
{
$match: {
username: "USERNAME" // or any other condition here
}
},
{
$lookup: {
from: "posts",
let: { username: "$username"},
pipeline: [
{$match : {"username" : "$$username"}},
{$group : {_id : "$username", "post_count" : {"$sum : 1"}}}
],
as: "posts"
}
},
{
$lookup: {
from: "comments",
pipeline: [
{$match : {"username" : "$$username"}},
{$group : {_id : "$username", "comment_count" : {"$sum : 1"}}}
],
as: "comments"
}
}
])