[英]MongoDB aggregate count of other collection
我想加入一个用户的评论数。
用户集合的示例:
{ ... email: "example1@mail.com", name: "Joe" },
{ ... email: "example2@mail.com", name: "Peter" }
以下是评论集合(存储超过 10 万个文档)中的几个示例:
{ ... author: "example1@mail.com", comment: "xxx" },
{ ... author: "example2@mail.com", comment: "yyy" },
{ ... author: "example1@mail.com", comment: "xxx" },
{ ... author: "example1@mail.com", comment: "xxx" }
我怎样才能达到以下结果:
{ ... email: "example1@mail.com", name: "Joe", comments: 3 }
{ ... email: "example2@mail.com", name: "Peter", comments: 1 }
您不需要使用此处提供的数据进行$lookup
。 您只需要将$group
和$sum
放入评论集合中,如下所示:
db.comment.aggregate([
{
"$group": {
"_id": "$author",
"comments": { "$sum": 1 } }
}
])
这里的例子
编辑以添加 $lookup
要从其他集合中获取数据,您可以使用$lookup
(它返回一个数组)和$arrayElemAt
来首先获取 object position。
使用此查询,您可以将其他集合数据放入user_data
字段。
db.comment.aggregate([
{
"$group": {
"_id": "$author",
"comments": {"$sum": 1}
}
},
{
"$lookup": {
"from": "user",
"localField": "_id",
"foreignField": "email",
"as": "user_data"
}
},
{
"$set": {
"user_data": {"$arrayElemAt": ["$user_data",0]}
}
}
])
这里的例子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.