简体   繁体   中英

Java Mongodb match regex to any document field

I have some documents like this.

{
    _id: "1234",
    code:"asdf",
    text:"aas23423",
    ....
{

I need to do a regex search on every value in my db. Is there a way to do something like the following?

public List<Document> findWithRegex(MongoCollection<Document> collection, String regex){
        Document findQuery = new Document();
        findQuery.append(/*any key in any document*/, Pattern.compile(regex));
        FindIterable<Document> iterable = collection.find(findQuery);
}

Or if that is not possible is there a way to || something like this together. Something like this.

collection.find(document -> document.code.matches(regex-pattern) || document.text.matches(regex-pattern))

Create another field which contains a concatenation of values from the existing fields, search that field.

If the fields are large, create another collection where documents have just the field used for the text search.

You should likely be using text search instead of regular expression queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM