首页 > 解决方案 > 如何使用mongo模板在mongoDB中提取字段的子字符串

问题描述

我在 mongo 集合“位置”中有一个字段“分支”。分支字段的格式类似于“India.Delhi.Saket”或有时是“India.Punjab”。我想从每条记录中提取第二个值并使用 mongo 模板对它们进行计数。

Ex.

|branch                 | branch_substring(Intermediate value)|
|-----------------------|-------------------------------------|
| India.Delhi.Saket     |      Delhi                          |
| India.Punjab          |      Punjab                         |
| India.Delhi           |      Delhi                          |

This should give output as follows

|branch |count|
|-------|-----|
|Delhi  | 2   |
|Punjab | 1   |

标签: mongodbmongotemplate

解决方案


  1. $project:生成带有country_branch(数组)字段的文档。运算符使用“.”将字符串$split拆分branch为字符串数组。作为分隔符。
  2. $groupcountry_branch: 用( )的第二个元素对所有文档进行分组$arrayElementAt并执行$count
  3. $sort: 按count降序排列。
  4. $projectbranch: 带有和count字段的项目文档。
db.collection.aggregate([
  {
    $project: {
      "country_branch": {
        "$split": [
          "$branch",
          "."
        ]
      }
    }
  },
  {
    $group: {
      "_id": {
        "branch": {
          "$arrayElemAt": [
            "$country_branch",
            1
          ]
        }
      },
      "count": {
        $count: {}
      }
    }
  },
  {
    "$sort": {
      "count": -1
    }
  },
  {
    $project: {
      "_id": 0,
      "branch": "$_id.branch",
      "count": "$count"
    }
  }
])

示例 Mongo Playground

输出

[
  {
    "branch": "Delhi",
    "count": 2
  },
  {
    "branch": "Punjab",
    "count": 1
  }
]

推荐阅读