问题描述
我想将3a这样的字母数字字符串拆分为“ 3”和“ a”。如果有人有想法请帮助。我不能在mongodb聚合中使用$ split。
解决方法
我不确定这是否有效,但是此答案可能会为您提供解决方案。
由于我们无法在$split
中使用正则表达式,
- 第一阶段-将句子分为单词并存储在
char[]
- 使用
char[]
平放$unwind
- 使用
strings[]
将所有字符串分类为numbers[]
,并将所有数字分类为$facet
。在这里,我们将$match
与regex
一起使用 - 然后根据需要进行组合。
假设这是您的字符串。
{
char:"32ab"
}
mongo脚本可能是
db.collection.aggregate([{$addFields: {
'char': {
$map: {
input: {
$range: [
0,{
$strLenCP: '$char'
}
]
},'in': {
$substrCP: [
'$char','$$this',1
]
}
}
}
}},{$unwind: {
path: '$char',preserveNullAndEmptyArrays: false
}},{$facet: {
strings: [
{
$match: {
'char': RegExp('^[A-Za-z]+$')
}
},{
$group: {
_id: null,arr: {
$push: '$char'
}
}
},{
$project: {
combined: {
$reduce: {
input: '$arr',initialValue: '','in': {
$concat: [
'$$value','$$this'
]
}
}
}
}
}
],numbers: [
{
$match: {
'char': {
$not: RegExp('^[A-Za-z]+$')
}
}
},'in': {
$concat: [
'$$value','$$this'
]
}
}
}
}
}
]
}},{$project: {
string: {
$arrayElemAt: [
{
$ifNull: [
'$strings.combined',''
]
},0
]
},number: {
$toInt:{
$arrayElemAt: [
{
$ifNull: [
'$numbers.combined',0
]
}
}
}}])
输出为
{
string : "ab",numbers: 32
}