Khon Lieu
Khon Lieu

Reputation: 4365

how to do a regex query on mongodb ObjectId field

this is a bit tricky.. how do you do a regex query on the ObjectId field?

i'm using the java api, so this is what i have so far

BasicDBObject q = new BasicDBObject()
q.put(field, Pattern.compile(value, Pattern.CASE_INSENSITIVE));

this works fine for any regular field. but doesn't seem to work with ObjectId field. which i assume is because i can't compare an ObjectId to a string? and i can't exactly just put a partial id or a regex into a new ObjectId. it'll just throw an error.

any ideas on this? i'm trying to give users a way to enter part of an id, and be able to get back all documents with that pattern.

thanks in advance!

Upvotes: 5

Views: 4836

Answers (1)

rocky3000
rocky3000

Reputation: 1120

As far as I know ObjectId is a own type in MongoDB and does not behave like a string. And although there are other types in MongoDB distinct from string, like arrays and so on, which are searchable by a regex pattern, this seems not possible for ObjectId. To implement an id search like yours I would probably define an own, indexed id field which contains an id as a simple string and cold-shoulder ObjectId.

Upvotes: 4

Related Questions