查找前缀字符串、Aggregate、MongoDB

uqcuzwp8  于 2022-10-22  发布在  Go
关注(0)|答案(1)|浏览(176)

我有这样一个简单的数据

{
 _id:1,
 code: "LAZ0101"
},
{
 _id:2,
 code: "LAZ1102"
},
{
 _id:3,
 code: "LAZA0101"
},
{
 _id:4,
 code: "LAZAB102"
}

如何使用这样的聚合对数据进行分组

{
 _id: "LAZ",
 count: 2
},
{
 _id: "LAZA",
 count: 2
}

使用聚合框架可以做到这一点吗?

hc8w905p

hc8w905p1#

使用$substr减去前4个字符,然后使用$group,然后使用$cond减去未分组的字符串
测试它here

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"
      }
    }
  },

])

相关问题