3

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.

1
  • I don't know Mongo regex syntax, but if the regex match applies to the entire string, then you'll have to use something like {name : /.*a.*/}. Commented Aug 12, 2018 at 5:39

2 Answers 2

3

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 ] }
        }
    }
])
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.