Mongodb: 如何通过$group内的另一个阶段?

Mongodb: How to pass another stage inside $group?



预期输出:

[
  {
    "_id": "healty",
    "doc_count": 2,
    "ingredients": {
      "Leaves": {
        "1.2g": 1,
        "1.5g": 1
      },
      "Spinach": {
        "12g": 1,
        "18g": 1
      }
    }
  },
  {
    "_id": "junk",
    "doc_count": 3,
    "ingredients": {
      "cheese": {
        "100g": 1,
        "120g": 2
      },
      "meat": {
        "50g": 1,
        "60g": 1,
        "70g": 1
      }
    }
  }
]

汇总如下:Playground1

db.collection.aggregate([
  {
    $group: {       
      "_id": "$type",  // grouping the document by "type" field
      "ingredients": {
        $push: "$$ROOT"  //want to run Playground2 aggrgtion in each of it
      },
      "doc_count": {
        $sum: 1        // total count
      }
    }
  }
])


之后,

我还想出了一个 Another Step 来转换 ingredients 数组:Playground2

但是,此聚合适用于所有文档。我想让 Playground2 聚合仅在每个 group Object.

的成分字段中起作用

这类似于组合 Playground1 & Playground2。我该怎么做?

db.collection.aggregate([
  {
    "$set": {
      "ingredients": {
        "$objectToArray": "$ingredients"
      }
    }
  },
  {
    "$unwind": "$ingredients"
  },
  {
    "$group": {
      "_id": {
        type: "$type",
        ingredient: "$ingredients"
      },
      "count": {
        "$sum": 1
      },
      "doc_count": {
        "$addToSet": "$item"
      }
    }
  },
  {
    "$group": {
      "_id": {
        type: "$_id.type",
        ingredient: "$_id.ingredient.k"
      },
      "docs": {
        "$push": {
          k: "$_id.ingredient.v",
          v: "$count"
        }
      },
      "doc_count": {
        "$push": "$doc_count"
      }
    }
  },
  {
    "$group": {
      "_id": "$_id.type",
      "ingredients": {
        "$push": {
          k: "$_id.ingredient",
          v: {
            "$arrayToObject": "$docs"
          }
        }
      },
      "doc_count": {
        "$push": {
          $reduce: {
            input: "$doc_count",
            initialValue: [],
            in: {
              $concatArrays: [
                "$$value",
                "$$this"
              ]
            }
          }
        }
      }
    }
  },
  {
    "$set": {
      "ingredients": {
        "$arrayToObject": "$ingredients"
      },
      doc_count: {
        "$size": {
          "$setUnion": {
            $reduce: {
              input: "$doc_count",
              initialValue: [],
              in: {
                $concatArrays: [
                  "$$value",
                  "$$this"
                ]
              }
            }
          }
        }
      }
    }
  }
])

mongoplayground