当前位置:网站首页>Mongodb——使用Mongodb对字段中字符串内容进行截取,并进行分组统计
Mongodb——使用Mongodb对字段中字符串内容进行截取,并进行分组统计
2022-06-26 05:59:00 【大·风】
最近忙的厉害,除了发一发之前写的存货只能写一些简单的东西了。
这里就简单分享下最近遇见针对数据进行指标统计遇见的问题。
针对字段中某部分内容的指标统计
在使用mongodb进行指标统计的时候可能遇见下面的数据结构
/* 1 */
{
"_id" : ObjectId("5edf4b5c64574814bc8ae4ae"),
"address" : "河南,信阳",
"state" : 0,
"remark" : "发送成功",
"createAt" : NumberLong(1591199999000)
}
/* 2 */
{
"_id" : ObjectId("5edf4ca064574814bc8ae4d5"),
"address" : "湖北,武汉",
"state" : 0,
"remark" : "发送成功",
"createAt" : NumberLong(1591199999000)
}
/* 3 */
{
"_id" : ObjectId("5edf4cac64574814bc8ae4d9"),
"address" : "湖北,宜昌",
"state" : 0,
"remark" : "发送成功",
"createAt" : NumberLong(1591199999000)
}
在某些时候我们可能需要根据地区信息来统计一些数据,但是数据并非是绝对干净的,可能只需要我们根据部分字段进行统计。
这个时候就需要使用$split或者使用$substr进行分组计算。
比如上面的数据中需要我们统计每个省下面业务数据内容。
使用split进行字符串截取
db.getCollection('AreaDemoLog').aggregate([
{
"$project": {
// 首先使用$split对address字段进行切割,得到名称为regions的地区数组
"regions": {
"$split": ["$address",","]
}
}
},
{
"$project": {
"regions": 1,
// 然后使用$arrayElemAt获得regions的地区数组中第一个元素,命名为 province
"province": {
"$arrayElemAt": [ "$regions",0]
}
}
},
{
"$group": {
// 最后根据province字段分组求总
"_id": "$province",
"count": {
"$sum": 1
}
}
},
{
"$project": {
"count": 1,
"_id": 0,
"province": "$_id"
}
}
])
使用substr进行字符串截取
db.getCollection('AreaDemoLog').aggregate([
{
"$project": {
// 首先使用$substrCP对address字段进行截取,然后直接得到目标字段
"province": {
$substrCP: [ '$address', 0, 2 ]
}
}
},
{
"$group": {
// 最后根据province字段分组求总
"_id": "$province",
"count": {
"$sum": 1
}
}
},
{
"$project": {
"count": 1,
"_id": 0,
"province": "$_id"
}
}
])
关于字符串截取注意
对于截取纯英文和数字的字符串结构的时候可以使用$substr但是使用纯汉字的字段进行截取的时候,使用$substr根据设置的编码情况会出现下面异常:
$substrBytes: Invalid range, ending index is in the middle of a UTF-8 character.
因为$substr仅适用于ASCII编码。所以这个时候需要使用mongodb 3.4中引入的$substrCP来进行字符串切割。
上面两个查询都可以得到正确结果
/* 1 */
{
"count" : 16.0,
"province" : "湖北"
}
/* 2 */
{
"count" : 1.0,
"province" : "河南"
}
将上面查询转换为JAVA代码
将上面查询语句放到JAVA代码中是下面的结构
使用split进行字符串截取
public static String test() {
List<AggregationOperation> lstOperations = new ArrayList<>(10);
// 切分地区
AggregationOperation splitAgg =
Aggregation.project().andExpression("{ $split: {'$address', ','}}").as("regions");
lstOperations.add(splitAgg);
ProjectionOperation province =
Aggregation.project("$regions").andExpression("{ $arrayElemAt: { '$regions', 0 }}").as("province");
lstOperations.add(province);
// 求总
AggregationOperation groupAgg = Aggregation.group("$province").count().as("count");
lstOperations.add(groupAgg);
// 定义查询内容
ProjectionOperation projectionOperation =
Aggregation.project("count").andExclude("_id").and("$_id").as("province");
lstOperations.add(projectionOperation);
AggregationOptions aggregationOptions = AggregationOptions.builder().allowDiskUse(true).build();
//开始查询
Aggregation agg = Aggregation.newAggregation(lstOperations).withOptions(aggregationOptions);
AggregationResults<Map> groupResult = this.mongoTemplate.aggregate(agg, "AreaDemoLog", Map.class);
return "";
}
使用substr进行字符串截取
public static String test() {
List<AggregationOperation> lstOperations = new ArrayList<>(10);
// 切分地区
ProjectionOperation province =
Aggregation.project().andExpression("{ $substrCP: { '$address', 0, 2 } }").as("province");
lstOperations.add(province);
// 求总
AggregationOperation groupAgg = Aggregation.group("$province").count().as("count");
lstOperations.add(groupAgg);
// 定义查询内容
ProjectionOperation projectionOperation =
Aggregation.project("count").andExclude("_id").and("$_id").as("province");
lstOperations.add(projectionOperation);
AggregationOptions aggregationOptions = AggregationOptions.builder().allowDiskUse(true).build();
//开始查询
Aggregation agg = Aggregation.newAggregation(lstOperations).withOptions(aggregationOptions);
AggregationResults<Map> groupResult = this.mongoTemplate.aggregate(agg, "AreaDemoLog", Map.class);
return "";
}
将上面查询转换为JAVA代码需要注意内容
在mongodb查询中我们使用了下面的语句
"$split": ["$address",","]
"$arrayElemAt": [ "$regions",0]
$substrCP: [ '$address', 0, 2 ]
在使用MongodbTemplate进行查询的假如直接使用下面的拼写
andExpression("{ $split: [ '$address', ',' ] }")
andExpression("{ $arrayElemAt: [ '$regions', 0] }")
andExpression("{ $substrCP: [ '$address', 0, 2 ] }")
最终的查询会出现下面异常
{
"code": 1,
"msg": "Expression [{ $split: ['$address', ',']}] @23: EL1043E: Unexpected token. Expected 'rsquare(])' but was 'comma(,)'"
}
所以在将上面语句转到JAVA中的语句时候需要将"[...]"修改为"{...}"
个人水平有限,上面的内容可能存在没有描述清楚或者错误的地方,假如开发同学发现了,请及时告知,我会第一时间修改相关内容。假如我的这篇内容对你有任何帮助的话,麻烦给我点一个赞。你的点赞就是我前进的动力。
边栏推荐
- What management systems (Updates) for things like this
- Posting - don't get lost in the ocean of Technology
- Multi thread synchronous downloading of network pictures
- REUSE_ ALV_ GRID_ Display event implementation (data_changed)
- About XXX management system (version C)
- Record how to modify the control across threads
- Household accounting procedures (the second edition includes a cycle)
- Prototype mode, Baa Baa
- REUSE_ALV_GRID_DISPLAY 事件实现(DATA_CHANGED)
- 状态模式,身随心变
猜你喜欢

Kolla ansible deploy openstack Yoga version

组合模式、透明方式和安全方式
从新东方直播来探究下小程序音视频通话及互动直播

Pytorch (network model training)

423-二叉树(110. 平衡二叉树、257. 二叉树的所有路径、100. 相同的树、404. 左叶子之和)

【C语言】深度剖析数据在内存中的存储

pytorch(网络模型训练)

小程序如何关联微信小程序二维码,实现二码聚合

通俗易懂的从IDE说起,再谈谈小程序IDE

Implementation of third-party wechat authorized login for applet
随机推荐
Consul service registration and discovery
REUSE_ ALV_ GRID_ Display event implementation (data_changed)
Machine learning 05: nonlinear support vector machines
Describe an experiment of Kali ARP in LAN
numpy. random. choice
MySQL database-01 database overview
cross entropy loss = log softmax + nll loss
Operator priority, associativity, and whether to control the evaluation order [detailed explanation]
numpy. frombuffer()
类和对象的学习
volatile应用场景
Definition of Halcon hand eye calibration
pytorch(网络模型)
Vs2022 offline installation package download and activation
Day3 - variables and operators
The most refined language interprets the event dispatcher (also known as the event scheduler)
[intra group questions semester summary] some reference questions for beginners
Getting to know concurrency problems
Given two corresponding point sets AB, how to estimate the parameters of the specified transformation matrix R?
Explore small program audio and video calls and interactive live broadcast from New Oriental live broadcast