5

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!

Khon Lieu
  • 4,295
  • 7
  • 37
  • 39

1 Answers1

4

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.

rocky3000
  • 1,134
  • 8
  • 9
  • well, you can always store the objectid as string and query it. The practical use of this approach is more than doubtful. –  Apr 10 '11 at 17:04
  • yeah, i was thinking the same thing...worse case, i'd have to store a new field that has the objectid as a string... – Khon Lieu Apr 10 '11 at 17:41
  • 2
    Rocky is correct; we store ObjectId as a special type in MongoDB. Specifically the native representation of ObjectId is stored more compactly than a string version. Remember that you don't have to use ObjectId for _id's value : It can be any valid type including a Document. If you need to do RE matching you should consider a diff type; but remember RE matches don't hit indexes unless '^' anchored. – Brendan W. McAdams Apr 10 '11 at 18:45