简体   繁体   English

MongoDB 按数组内的字符串字段分组

[英]MongoDB Group by String Field inside of an Array

I did a lot of research on MongoDB aggregation grouping, but couldn't find a solution.我对 MongoDB 聚合分组进行了大量研究,但找不到解决方案。

I have the following document structure:我有以下文档结构:

{
  "_id":"6053e0ef22b8e60015a23da8",
  "shoppinglist":[
     {
        "_id":"606ae2e34e4416001538104f",
        "items":[
           {
              "_id":"6071c5ed8f669f0015e6eebe",
              "product_id":"605852c28ea29f0015653d6f",
           },
           ...
        ]
     }
}

My goal is to group the items in each shopping list object using the product_id , so that my result looks like this:我的目标是使用product_id对每个购物清单 object 中的项目进行分组,因此我的结果如下所示:

{
  "_id":"6053e0ef22b8e60015a23da8",
  "shoppinglist":[
     {
        "_id":"606ae2e34e4416001538104f",
        "items":[
           {
              "_id":"6071c5ed8f669f0015e6eebe",
              "product_id":"605852c28ea29f0015653d6f",
              "count": 3 //3 items with the product_id = 605852c28ea29f0015653d6f
           },
           ...
        ]
     }
}

Can someone help me with this, I'm desperate.有人可以帮我解决这个问题,我很绝望。

  • $unwind deconstruct shoppinglist array $unwind解构shoppinglist清单数组
  • $unwind deconstruct shoppinglist.items array $unwind解构shoppinglist.items数组
  • $group by _id and product_id , and get required fields using $first and get count using $sum $group by _idproduct_id ,并使用$first获取必填字段并使用$sum获取计数
  • $group by _id and shoppinglist._id and reconstruct array of items $group by _idshoppinglist._id并重建项目数组
  • $group by _id and reconstruct array of shoppinglist $group by _id并重建shoppinglist清单数组
db.collection.aggregate([
  { $unwind: "$shoppinglist" },
  { $unwind: "$shoppinglist.items" },
  {
    $group: {
      _id: {
        _id: "$_id",
        product_id: "$shoppinglist.items.product_id"
      },
      shoppinglist_id: { $first: "$shoppinglist._id" },
      items_id: { $first: "$shoppinglist.items._id" },
      count: { $sum: 1 }
    }
  },
  {
    $group: {
      _id: {
        _id: "$_id._id",
        shoppinglist_id: "$shoppinglist_id"
      },
      items: {
        $push: {
          items_id: "$items_id",
          product_id: "$_id.product_id",
          count: "$count"
        }
      }
    }
  },
  {
    $group: {
      _id: "$_id._id",
      shoppinglist: {
        $push: {
          _id: "$_id.shoppinglist_id",
          items: "$items"
        }
      }
    }
  }
])

Playground操场

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

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