我有这样一个简单的数据
{ _id:1, code: "LAZ0101" }, { _id:2, code: "LAZ1102" }, { _id:3, code: "LAZA0101" }, { _id:4, code: "LAZAB102" }
如何使用这样的聚合对数据进行分组
{ _id: "LAZ", count: 2 }, { _id: "LAZA", count: 2 }
使用聚合框架可以做到这一点吗?
hc8w905p1#
使用$substr减去前4个字符,然后使用$group,然后使用$cond减去未分组的字符串测试它here
$substr
$group
$cond
db.collection.aggregate([ { $project: { code: { $substr: [ "$code", 0, 4 ] } } }, { "$group": { "_id": "$code", "count": { "$sum": 1 } } }, { $project: { count: 1, _id: { "$cond": { "if": { $gt: [ "$count", 1 ] }, "then": "$_id", "else": { $substr: [ "$_id", 0, 3 ] } }, } } }, { "$group": { "_id": "$_id", "count": { "$sum": "$count" } } }, ])
1条答案
按热度按时间hc8w905p1#
使用
$substr
减去前4个字符,然后使用$group
,然后使用$cond
减去未分组的字符串测试它here