简体   繁体   中英

Spring MongoDB search id by string

I have a simple spring web application which uses mongodb. I have a requirement of searching the collection id by string, where the string should work regex Statement. My criteria creating method looks like this.

public Criteria getSearchCriteriaQuery(String keyword, String colomnArray[]){
    Criteria[] criteriaList = new Criteria[colomnArray.length];
    for (int i=0; i<colomnArray.length; i++) {
        criteriaList[i] = Criteria.where(colomnArray[i]).regex(keyword, "i");
    }
    return this.criteria.orOperator(criteriaList);
}

My domain looks like this

@Document
public class sampleDomain{

@Id
private String id;
....
}

When I use "id" / "_id" as the column name, it does not return anything even if I send a valid string as keyword. example query I tried is given below

id in db - 560299fe627942619bcfdc87
keyword - 560

Is there a solution for this? Thanks in advance

This is not going to work I think. A MongoDb ID is not a String but an ObjectId which can be represented as a String but not handled as one. So doing a regex on an ObjectId would mean mongo would have to unpack every ObjectId to a String and then do the regex on it. That would be crazily inefficient.

Unless Spring-data-mongo has something up his sleeves, you might need to rethink your model and your queries.

Because this is a strange use case for MongoDB to do a regex on an ObjectId. Can you explain why you are doing this and why you are not using another field to do the regex on?

Kind regards Chris

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