mongodb - 如何使用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 |
解决方案
$project
:生成带有country_branch
(数组)字段的文档。运算符使用“.”将字符串$split
拆分branch
为字符串数组。作为分隔符。$group
country_branch
: 用( )的第二个元素对所有文档进行分组$arrayElementAt
并执行$count
。$sort
: 按count
降序排列。$project
branch
: 带有和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"
}
}
])
输出
[
{
"branch": "Delhi",
"count": 2
},
{
"branch": "Punjab",
"count": 1
}
]
推荐阅读
- javascript - 如何将数据从 Meteor 应用程序发送到嵌入式小部件?
- c++ - 用 GTK3 C++ 获取指针坐标
- sql - 数据库设计,减少join
- python - 如何将 PyTorch 子模块保持在 eval 模式?
- redis-cluster - redis集群重定向到另一台服务器并给出身份验证错误
- asp.net-core - 使用来自单独程序集的启动类的 ASP.NET Core MVC 问题
- javascript - 等待似乎不是在等待我的函数中的结果
- reactjs - 带有条件渲染的 React Native Firebase onAuthStateChanged 给出警告 Can't perform a React state update
- c# - 鼠标运动的熵
- python - 多屏幕上的 Kivy 相机