簡體   English   中英

MongoDB 獲取聚合最后階段的字段總和

[英]MongoDB get sum of fields in last stage of aggregate

我正在使用聚合來收集一些相關數據。 以下是將父集合連接到子集合的示例管道(每個父集合都有一個子集合)。

然后我使用投影從 collections 中收集一些字段。 這包括計算孩子擁有的“蘇打水數量”。

最終,我的目標是獲得所有孩子擁有的所有蘇打水的總數(所以基本上是投影中childSodaCount字段的總和。

我通過在管道末端附加一個group階段來嘗試這一點。 這確實有效,但是,我從投影中丟失了所有其他字段。

有什么見解嗎?

[
  {
    '$lookup': {
      'from': 'Children', 
      'localField': 'childId', 
      'foreignField': '_id', 
      'as': 'CHILDREN'
    }
  } {
    '$unwind': {
      'path': '$CHILDREN' 
    }
  } {
    '$project': {
      'childSodaCount': {
        '$size': '$CHILDREN.sodas'
      }, '
      'parentName': 1, 
      'parentFoo': 1, 
      'parentBar': 1, 
     
      'childName': {
        '$concat': [
          '$CHILDREN.firstName', ' ', '$CHILDREN.lastName'
        ]
      }, 
    {
    '$group': {
      '_id': null, 
      'TOTAL_CHILD_SODA_COUNT': {
        '$sum': '$childSodaCount'
      }
    }
  }
]

基本上$group by null 會將所有文檔分組到一個文檔中,嘗試$facet$project階段之后將兩個結果分開,

{
  $facet: {

    // All documents
    docs: [ { $match: {} } ],

    // Total child soda
    TOTAL_CHILD_SODA_COUNT: [
      {
        $group: {
          _id: null,
          count: {
            $sum: "$childSodaCount"
          }
        }
      }
    ]

  }
}

這將導致類似,

[
  {
    docs: [{}, {}, .. all docs]
    TOTAL_CHILD_SODA_COUNT: [{ _id: null, count: 1 }] // total count
  }
]

如果您想獲得直接計數而不是 object 數組,請在$facet階段之后嘗試$addFields階段,

{
  $addFields: {
    TOTAL_CHILD_SODA_COUNT: { $arrayElemAt: ["$TOTAL_CHILD_SODA_COUNT.count", 0] }
  }
}

你的最終結果將是,

[
  {
    docs: [{}, {}, .. all docs]
    TOTAL_CHILD_SODA_COUNT: 1 // total count
  }
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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