简体   繁体   中英

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):

{ ... 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. You only need $group and $sum into comments collection like this:

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

Example here

Edit to add $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.

With this query you have the other collection data into user_data field.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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