MongoError: PlanExecutor error during aggregation

MongoError: PlanExecutor error during aggregation

我在 mongodb 中有树木记录,但可能还有更多,我通过来自前端的 ID 获取商店

我需要获取 20 条记录并按 itemId 和 colorId 对它们进行分组,并获取每家商店的计数。商店的数量可以是 1,2,3,....10etc..

这是我需要的输出:

+--------+----------+-------+-------+-------+
| itemId | colorId  | shop1 | shop2 | shop3 |
+========+==========+=======+=======+=======+
| 1      | colorId1 | 5     | 0     | 3     |
+--------+----------+-------+-------+-------+
| 2      | colorId2 | 3     | 0     | 0     |
+--------+----------+-------+-------+-------+
| 3      | colorId2 | 0     | 3     | 0     |
+--------+----------+-------+-------+-------+
| 2      | colorId1 | 0     | 5     | 0     |
+--------+----------+-------+-------+-------+
| 3      | colorId1 | 0     | 0     | 5     |
+--------+----------+-------+-------+-------+

here is my data and query - 这里的 shopId 是字符串,效果很好。

但是当我在我的本地机器上使用这个查询时,我得到这个错误:

MongoError: PlanExecutor error during aggregation :: caused by :: $arrayToObject 需要一个带有键 'k' 和 'v' 的对象,其中 'k' 的值必须是字符串类型。找到类型:objectId

但是当我将 shopId 更改为 ObjectId 时出现错误。 ObjectId versoin

根据您在评论中的要求(如果我没看错的话):

    db.collection.aggregate([
  {
    "$match": {}// <-- Highly recommend you to use match due to the complexity of this query
  },
  {
    $group: {
      _id: 0,
      data: {
        $push: {
          shopId: "$shopId",
          shopItems: "$shopItems"
        }
      },
      shopIds: {
        "$push": {
          shopId: "$shopId",
          "count": 0
        }
      }
    }
  },
  {
    $unwind: "$data"
  },
  {
    $unwind: "$data.shopItems"
  },
  {
    $group: {
      _id: {
        itemId: "$data.shopItems.itemId",
        colorId: "$data.shopItems.colorId"
      },
      data: {
        $push: {
          shopId: "$data.shopId",
          count: "$data.shopItems.itemCount"
        }
      },
      existing: {
        $push: {
          shopId: "$data.shopId",
          "count": 0
        }
      },
      shopIds: {
        $first: "$shopIds"
      }
    }
  },
  {
    "$addFields": {
      "missing": {
        "$setDifference": [
          "$shopIds",
          "$existing"
        ]
      }
    }
  },
  {
    $project: {
      data: {
        $concatArrays: [
          "$data",
          "$missing"
        ]
      }
    }
  },
  {
    $unwind: "$data"
  },
  {
    $sort: {
      "data.shopId": 1
    }
  },
  {
    $group: {
      _id: "$_id",
      counts: { // here you can change this key
        $push: "$data"
      },
      totalCount: {
        $sum: "$data.count" // if you want it
      }
    }
  }
])

在第一个$match之后,我们$group为了获取每个文档中的所有shopId。 接下来我们按您想要的组 $unwind$group:按 colorId 和 itemId。然后我们添加所有计数为 0 的商店并删除具有实际计数的商店。最后三个步骤仅用于排序、求和和格式化。 你可以玩玩它 here.