MongoError:聚合期间 PlanExecutor 错误
我在 mongodb 中有树记录,但可能还有更多,我通过来自前端的 ID 获取商店,
我需要获取 20 条记录并按 itemId 和 colorId 对它们进行分组,并获取每个商店的计数。商店数量可以是 1,2,3,....10 等..
这是我需要的输出:
+--------+----------+-------+-------+-------+
| 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是我的数据和查询 - 这里 shopId 是字符串,它工作得很好。
但是当我在本地机器上使用此查询时,我收到此错误:
MongoError: PlanExecutor error duringaggregation ::造成的::$arrayToObject需要一个带有键“k”和“v”的对象,其中“k”的值必须是字符串类型。找到类型:objectId,
但是当我将 shopId 更改为 ObjectId 时,出现错误。 ObjectId 版本
I have tree records in mongodb but there could be many more, I'm getting shops by an ID coming from frontend
I need to get 20 records and group them by itemId and colorId, and get counts for every shop. the count of shops can be 1,2,3,....10etc..
this is output I need:
+--------+----------+-------+-------+-------+
| 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 - here shopId is string and it's work good.
but when I use this query on my local mashine, I'm getting this error:
MongoError: PlanExecutor error during aggregation :: caused by :: $arrayToObject requires an object with keys 'k' and 'v', where the value of 'k' must be of type string. Found type: objectId
but when I change shopId to the ObjectId I'm getting error.
ObjectId versoin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据您在评论中的请求(如果我做对了):
在第一个
$match
之后,我们$group
以便获取每个文档中的所有 shopId。接下来,我们按您想要的组
$unwind
和$group
:按 colorId 和 itemId。然后我们添加所有计数为 0 的商店并删除实际计数的商店。最后三个步骤仅用于排序、求和和格式化。您可以在此处使用它。
Per your request in the comments (if I got it right):
After the first
$match
, we$group
in order to get all shopIds in each document.Next we
$unwind
and$group
by the group you wanted: by colorId and itemId. Then we are adding all the shops with count 0 and removing the ones that do have actual count. Last three steps are just for sorting, summing and formating.You can play with it here.