像这样的收藏品
{ _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管道中的regex条件表达式。那么,我们如何通过查询进行转换-然后分组呢?我想其中一种方法是通过MapReduce,但据说性能并不好。特别是我的应用程序使用python,使用MapReduce将JS代码和python代码结合在一起。
发布于 2017-05-02 07:49:05
您不需要MapReduce。您可以使用聚合框架进行此操作。
还请注意,不需要首先$project文档,可以将$switch表达式传递给_id
db.items.aggregate(
[
{
"$group": {
"_id": {
"$switch": {
"branches": [
{
"case": {
"$or": [
{
"$gt": [
{
"$indexOfCP": [
"$name",
"magazine"
]
},
-1
]
},
{
"$gt": [
{
"$indexOfCP": [
"$name",
"novel"
]
},
-1
]
}
]
},
"then": "book"
},
{
"case": {
"$or": [
{
"$gt": [
{
"$indexOfCP": [
"$name",
"violin"
]
},
-1
]
},
{
"$gt": [
{
"$indexOfCP": [
"$name",
"guitar"
]
},
-1
]
}
]
},
"then": "instrument"
}
],
"default": "others"
}
},
"count":{"$sum": "$qty"}
}
}
]
)db.items.aggregate(
[
{
"$group": {
"_id": {
"$switch": {
"branches": [
{
"case": {
"$gt": [
{
"$size": {
"$setInterserction": [
{
"$split": [
"$name",
"-"
]
},
[
"magazine",
"novel"
]
]
}
},
0
]
},
"then": "book"
},
{
"case": {
"$gt": [
{
"$size": {
"$setInterserction": [
{
"$split": [
"$name",
"-"
]
},
[
"guitar",
"violin"
]
]
}
},
0
]
},
"then": "instrument"
}
],
"default": "others"
}
},
"count": {"$sum": "$qty"}
}
}
]
)https://stackoverflow.com/questions/43732058
复制相似问题