【发布时间】:2023-03-07 23:32:01
【问题描述】:
对于这样的收藏
{ _id: 1, name: "novel_1", qty: 15}
{ _id: 2, name: "magazine_1", qty: 5}
{ _id: 3, name: "novel_2", qty: 5}
{ _id: 4, name: "guitar_1", qty: 10}
{ _id: 5, name: "violin_1", qty: 10}
我想以某种方式使用 $project 管道根据项目名称对项目进行分类。然后从中得到一个分组计数。
db.items.aggregate([
{$project: {category: {
$switch: {
branches: [
// use regex here to categorize the items by their name
{case: {$in: ['$name', [/magazine/, /novel/]]},
then: 'book'},
{case: {$in: ['$name', [/guitar/, /violin/]]},
then: 'instrument'}
],
default: 'others'
}
}}},
// get the group-by count based on the category
{$group: {
_id: {category: '$category'},
count: {$sum: '$qty'}
}}
]);
然而,MongoDB 似乎不支持 $project 管道中的正则表达式条件表达式。那么我们如何进行这种先变换后分组查询呢?我想一种方法是通过 MapReduce,但据说性能不是很好。特别是我在我的应用程序中使用 python,使用 MapReduce 会将 JS 代码和 python 代码缠在一起。
【问题讨论】:
标签: python mongodb mongodb-query aggregation-framework