Manipulate strings in mongodb that match the regex search

56 Views Asked by At

In java this is possible

public static void main(String[] args) {
    Matcher m = Pattern .compile("^(.*?[.].*?[.].*?[.].*?)[.].*")
                        .matcher(
                                "com.SEM.Google.Generico.space.test");
    if (m.matches()) {
        System.out.println(m.group(1));
    }
}

This would give me as result: com.SEM.Google.Generico

If I have a string in mongodb

"dv" : "com.SEM.Google.Generico.space.test"

can I use the mongo aggregation framework somehow to get com.SEM.Google.Generico as result?

It should be as generic as possible. So not something like

$project: {
    pathString: {
        $substr: ["$path.dv", 0, 23]
    }

}

Is this possible at all? Thanks.

2

There are 2 best solutions below

0
felix On BEST ANSWER

No, there is no way to do this.

This feature has been requested two years ago, but it hasn't been implemented yet ( see the open jira issue: https://jira.mongodb.org/browse/SERVER-11947 ). If you don't want to use $substr I guess that you should apply the regex on the query results...

0
satish chennupati On
var pattern = "Your Regex Pattern"
db.yourCollectionName.find( { "dv": { $regex: pattern} } )

should produce the desired results