Aliaaa
Aliaaa

Reputation: 1668

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.

Upvotes: 3

Views: 2265

Answers (2)

Raphael
Raphael

Reputation: 562

It's possible in Mongo 4.2 and up by using $regexMatch.

db.collection.aggregate([
  {
    $addFields: {
      "hasA": {
        $regexMatch: { input: "$name", regex: "a" }
      }
    }
  }
])

Upvotes: 1

mickl
mickl

Reputation: 49985

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 ] }
        }
    }
])

Upvotes: 3

Related Questions