简体   繁体   English

MongoDB 其他集合的合计计数

[英]MongoDB aggregate count of other collection

I want to join the number of comments of a user.我想加入一个用户的评论数。

An exmaple of the user collection:用户集合的示例:

{ ... email: "example1@mail.com", name: "Joe" },
{ ... email: "example2@mail.com", name: "Peter" }

And these are a couple of examples from the comments collection (which stores more than 100k documents):以下是评论集合(存储超过 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" }

How can I achieve the following result:我怎样才能达到以下结果:

{ ... email: "example1@mail.com", name: "Joe", comments: 3 }
{ ... email: "example2@mail.com", name: "Peter", comments: 1 }

You don't need a $lookup with data provided here.您不需要使用此处提供的数据进行$lookup You only need $group and $sum into comments collection like this:您只需要将$group$sum放入评论集合中,如下所示:

db.comment.aggregate([
  {
    "$group": {
      "_id": "$author",
      "comments": { "$sum": 1 } }
  }
])

Example here这里的例子

Edit to add $lookup编辑以添加 $lookup

To get data from the other collection you can use $lookup (which returns an array) and $arrayElemAt to get the object at first position.要从其他集合中获取数据,您可以使用$lookup (它返回一个数组)和$arrayElemAt来首先获取 object position。

With this query you have the other collection data into user_data field.使用此查询,您可以将其他集合数据放入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]}
    }
  }
])

Example here这里的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM