Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB adding field by regex condition

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.

like image 508
Aliaaa Avatar asked Dec 17 '25 14:12

Aliaaa


1 Answers

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 ] }
        }
    }
])
like image 75
mickl Avatar answered Dec 20 '25 15:12

mickl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!