簡體   English   中英

MongoDB 其他集合的合計計數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM