4

I would like to query a collection in a MongoDB database to find all records that contain a portion of an ObjectID. For a normal string I can use a regex like this:

db.teams.find({"some_string": /^51eed/})

But how would I do something similar on an ObjectID?

Specifically, I have a collection that looks something like this:

{ "status" : 0, "_id" : ObjectId("51e97ff613e737801d000002") }
{ "status" : 0, "_id" : ObjectId("51ee7513d1f7c57420000002") }
{ "status" : 0, "_id" : ObjectId("51eed9dd5b605af404000002") }
{ "status" : 0, "_id" : ObjectId("51eedab39108d8101c000002") }

I would like to query (in mongo) for all records where the ObjectId starts with "51eed". Your help is greatly appreciated.

rasmeister
  • 1,986
  • 1
  • 13
  • 19

2 Answers2

5

You can simply do this with a range search, start at "51eed0000000000000000000" and end at "51eee0000000000000000000" (notice the "d" -> "e"):

db.teams.find( { 
    _id: {
        $gte: ObjectId("51eed0000000000000000000"),
        $lt:  ObjectId("51eee0000000000000000000"),
    } 
} )
Derick
  • 35,169
  • 5
  • 76
  • 99
1

You could possibly just put that into a new ObjectId and fill the rest with 0's like:

db.teams.find({_id:{$gte:ObjectId("51eed0000000000000000000")}})

Should do the trick.

Sammaye
  • 43,242
  • 7
  • 104
  • 146