How to delete the strings before the first occurrence, and after the last occurrence of the delimiter? The delimiter is an underscore "_".
Sample data is:
[
{
"originalValue": "DELETERANDOMVALUE_Keep_This_Words_DELETERANDOMVALUE"
}
]
The expected result should be:
[
{
"cleanedValue": "Keep_This_Words"
}
]
With the below code, the string before the first occurrence of the delimiter is removed. But I am unable to delete the strings after the last occurrence.
db.collection.aggregate([
{
$project: {
_id: 0,
cleanedValue: {
$substr: [
"$originalValue",
{
$add: [
{
$indexOfBytes: [
"$originalValue",
"_"
]
},
1
]
},
{
"$strLenBytes": "$originalValue"
}
]
}
}
}
])
Here is a playground I used.
Thank you for the help.
2
Answers
Try to split the string into an array, remove the first and last element and return the joined string:
Link to playground.
You can find
first
andlast
unwanted parts using$regexFind
and then use$replaceAll
to replace them with empty strings. Like this:Playground link.