1

I need to check if the concatenation of two fields matches a particular regex. Here there is my code:

BasicDBObject regexQueryName = new BasicDBObject();
regexQueryCode.put("name", new BasicDBObject("$regex", ".*"+parameter+".*").append("$options", "i"));

BasicDBObject regexQuerySurname = new BasicDBObject();
regexQueryTitle.put("surname", new BasicDBObject("$regex", ".*"+parameter+".*").append("$options", "i"));

BasicDBList or = new BasicDBList();
or.add(regexQueryName);
or.add(regexQuerySurname);
BasicDBObject query = new BasicDBObject("$or", or);

it checks if the regex matches the first or the second field and then shows the result, while i need to concatenate the two fields before checking the regex. Please don't suggest me to use a view.

Thank you

  • You really don't want that as what you are doing is perfectly fine and the most efficient way to do so ( outside of a full text search ). Concatenating strings and then searching that "computed" result requires an aggregation pipeline and effectively writes a copy of your whole collection before any searching happens at all. It's basically "forced" and therefore simply better to search the fields with natural query operators. But it's of course been long answered if you want to look. – Neil Lunn Jun 02 '18 at 10:30

0 Answers0