【发布时间】:2019-03-03 03:14:46
【问题描述】:
我开始为 Mongo 学习聚合,但在我的项目中,我发现我的收藏中有很多名称非常相似的品牌,例如“BrandA”和“BrandA tech”。有没有办法在我的聚合结束时对它们进行分组?
我的数据库中有 2 个集合:
第一个是针对品牌的:
{
_id: ObjectId(),
name: String
}
第二个是针对产品的:
{
_id: ObjectId(),
name: String,
brand: ObjectId() // referring to _id of brands
}
现在假设我有以下品牌:
{_id: ObjectId('5a9fd2b8045b020013de2a47'), name: 'brand1'},
{_id: ObjectId('5a9fcf94d28420245451a39c'), name: 'brand2'},
{_id: ObjectId('5a9fcf94d28420245451a39a'), name: 'brand1 sub1'},
{_id: ObjectId('5a9fe8bf045b020013de2a6d'), name: 'sub2 brand2'}
以及以下产品:
{_id: ObjectId(''), name: 'item1', brand: ObjectId('5a9fd2b8045b020013de2a47')},
{_id: ObjectId(''), name: 'item2', brand: ObjectId('5a9fcf94d28420245451a39c')},
{_id: ObjectId(''), name: 'item3', brand: ObjectId('5a9fd2b8045b020013de2a47')},
{_id: ObjectId(''), name: 'item4', brand: ObjectId('5a9fcf94d28420245451a39a')},
{_id: ObjectId(''), name: 'item5', brand: ObjectId('5a9fe8bf045b020013de2a6d')},
{_id: ObjectId(''), name: 'item6', brand: ObjectId('5a9fd2b8045b020013de2a47')},
{_id: ObjectId(''), name: 'item7', brand: ObjectId('5a9fcf94d28420245451a39c')},
{_id: ObjectId(''), name: 'item8', brand: ObjectId('5a9fcf94d28420245451a39a')}
我现在的查询:
db.getCollection('products').aggregate([
{$group: {
_id: '$brand',
amount: { $sum: 1 },
}},
{
$sort: { 'amount': -1 }
},{$lookup: {
from: 'brands',
localField: '_id',
foreignField: '_id',
as: 'lookup'
}},
{$unwind: {path: '$lookup'}},
{$project: {
_id: '$_id',
brandName: '$lookup.name',
amount: '$amount'
}}
]);
结果:
{_id: ObjectId('5a9fd2b8045b020013de2a47'), brandName: 'brand1', amount: 3}
{_id: ObjectId('5a9fcf94d28420245451a39c'), brandName: 'brand2', amount: 2}
{_id: ObjectId('5a9fcf94d28420245451a39a'), brandName: 'brand1 sub1', amount: 2}
{_id: ObjectId('5a9fe8bf045b020013de2a6d'), brandName: 'sub2 brand2', amount: 1}
我想要的结果:
{_id: ObjectId(null), brandName: 'brand1', amount: 5},
{_id: ObjectId(null), brandName: 'brand2', amount: 3}
是否可以通过在品牌名称中找到类似的字符串来对我现在的结果进行分组?喜欢将 'brand1' 和 'brand1 sub1' 或 'brand2' 和 'sub2 brand2' 分组?
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework