How to apply regex on integer values in mongodb

I am using mongo aggregation like match,project,sort.
generation of query is happenning based on multiple crierias

Criteria.where(fieldname).is("somevalue"),
Criteria.where(fieldname).regex("regexvalue");

Using Aggregation like:-

newAggregation(
   match(new Criteria.andOperator(criteriaList)),
   project().and("userAddress.zipCode").as("zipCode")),
   sort(Sort.by("fieldName").ascending())
);

zipCode is string as of now but is there any way I can apply regex on zipCode or any Integer values. and also sort string(number) values based on integer sort order ascending or descending .

hi @shailee_kumari ,

By definition regex is applied on strings so I don’t see how it can work on int field.

What you can do is convert the string into an integer on your projection stage and therefore application will receive a numeric value if it needs to. But for regex search I would store as string.

Thanks
Pavel

1 Like

Is there any reason you need it to be a number? You can sort strings, especially zip codes as they are normalized to same number of characters the sort should be exactly equivalent as if they were converted to numbers…

Asya