I have several documents, I want to remove the alphabet from the data
field, based on the 1st _
in the data
field, please see the following output. and if the data is empty the get message "Not Auto found".
[
{
"data": "ABCS_auto"
},
{
"data": "TRQWEY_car_2"
},
{
"data": "ALPHAB1234RAVO_Garie_2__4_22__11"
},
{
"data": ""
}
]
Expected Output:
[
{
"data": "auto"
},
{
"data": "car_2"
},
{
"data": "Garie_2__4_22__11"
},
{
"data": "No Auto found"
}
]
3
Answers
Try this one:
Use $ifNull for "No Auto Found" and $split for "_"
here is a working mongoplayground link
$set
– Setsplit_data
field:1.1. If
data
not empty string, then split by "_" and return array.1.2. Else return empty array.
$project
– Decorate output document.2.1. If
split_data
is not empty array, then2.1.1.
$trim
starting "_" from the result 2.1.1.1.2.1.1.1. With
$reduce
, concatenate string with "_" from the result remove the first item fromsplit_data
.2.2. Else default message.
Sample Mongo Playground
Another approach I think is much easier is with
$regexFind
:$set
– Createdata_regex
field with regex match object by searching "_ .*" (Mean string starting with "_" and any other character(s)).$project
– Decorate output document.2.1. Trim the "_" from
data_regex.match
.2.2. Else default message.
Sample Mongo Playground (
$regexFind
)