Consider this simple collection:
{
"_id" : ObjectId("5b6fbcb328d62424ece9265b"),
"name" : "abc"
}
{
"_id" : ObjectId("5b6fbcbd28d62424ece9265c"),
"name" : "cde"
}
I want to add a field hasA which determines there is any 'a' character in name field in an aggregation query, so my expected output should be like this:
{
"_id" : ObjectId("5b6fbcb328d62424ece9265b"),
"name" : "abc",
"hasA" : true
}
{
"_id" : ObjectId("5b6fbcbd28d62424ece9265c"),
"name" : "cde",
"hasA" : false
}
I have tested this aggregation query but it returns wrong output:
$addFields
{
"hasA": { $cond : [ {name : /a/}, true, false ] }
}
output:
{
"_id" : ObjectId("5b6fbcb328d62424ece9265b"),
"name" : "abc",
"hasA" : true
}
{
"_id" : ObjectId("5b6fbcbd28d62424ece9265c"),
"name" : "cde",
"hasA" : true
}
I have tested many data with this query but it seems that it returns always true as result.
You can't use regular expressions in Aggregation Framework (JIRA ticket here). If you just need to check if string contains substring you can use $indexOfBytes operator which returns -1 if there's no match:
db.col.aggregate([
{
$addFields: {
"hasA": { $cond : [ { $eq: [ { $indexOfBytes: [ "$name", "a" ] }, -1 ] }, false, true ] }
}
}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With