MongoDB聚合组条件

问题描述 投票:0回答:1

我有以下集合,我想使用 MongoDB 聚合来实现以下输出。

 [
  {
    "order_line_item_id": 1
    "order_id": 100,
    "products": [
      {"name": "Shoe","hasDefect": "YES",},
      {"name": "Pant","hasDefect": "NO",},
      {"name": "Shirt","hasDefect": "NOT_SURE",},
    ],
  },
  {
    "order_line_item_id": 2
    "order_id": 100,
    "products": [
      {"name": "Shoe","hasDefect": "YES",},
      {"name": "Pant","hasDefect": "YES",},
      {"name": "Shirt","hasDefect": "YES",},
    ],
  },
  {
    "order_line_item_id": 3
    "order_id": 101,
    "products": [
      {"name": "Shoe","hasDefect": "YES",},
      {"name": "Pant","hasDefect": "NO",},
      {"name": "Shirt","hasDefect": "NOT_SURE",},
    ],
  },
]

我想按订单对它们进行分组,并根据条件在订单级别汇总“hasDefect”:

  1. 如果同一订单的各个订单行项目中的同一产品全部为“YES”,则该产品将在订单级别具有该产品的“YES”值。
  2. 如果是“YES”、“NO”和“NOT_SURE”的混合,则订单上会有“NO”
  3. 如果是“YES”和“NOT_SURE”的混合,订单上会有“NOT_SURE”

对于上述集合,对于订单 id:100,预期输出类似于:

[
    {
        "order_id": 100,
        {
        "products": [
          {"name": "Shoe","hasDefect": "YES",},
          {"name": "Pant","hasDefect": "NO",},
          {"name": "Shirt","hasDefect": "NOT_SURE",},
        }
    }
]
mongodb aggregation-framework
1个回答
0
投票
  1. $unwind
    - 将
    products
    数组解构为多个文档。

  2. $group
    - 按
    order_id
    products_name
    分组。添加值为
    hasDefects
    products.hasDefect
    数组。

  3. $set
    - 设置
    hasDefect
    字段。按条件对状态进行分类 (
    $switch
    )。

  4. $group
    - 按
    _id.order_id
    分组。添加
    products
    数组。

db.collection.aggregate([
  {
    $unwind: "$products"
  },
  {
    $group: {
      _id: {
        order_id: "$order_id",
        productName: "$products.name"
      },
      hasDefects: {
        $push: "$products.hasDefect"
      }
    }
  },
  {
    $set: {
      hasDefect: {
        $switch: {
          branches: [
            {
              case: {
                $allElementsTrue: {
                  $map: {
                    input: "$hasDefects",
                    as: "d",
                    in: {
                      $eq: [
                        "$$d",
                        "YES"
                      ]
                    }
                  }
                }
              },
              then: "YES"
            },
            {
              case: {
                $in: [
                  "NO",
                  "$hasDefects"
                ]
              },
              then: "NO"
            },
            {
              case: {
                $in: [
                  "NOT_SURE",
                  "$hasDefects"
                ]
              },
              then: "NOT_SURE"
            }
          ],
          default: "<DEFAULT>"
        }
      }
    }
  },
  {
    $group: {
      _id: "$_id.order_id",
      products: {
        $push: {
          name: "$_id.productName",
          hasDefect: "$hasDefect"
        }
      }
    }
  }
])

演示@Mongo Playground

© www.soinside.com 2019 - 2024. All rights reserved.