regexmongodb

Searching mongodb _id field using regex


In my sandbox I have a collection, and the unique key (_id) for the collection is a unique string from another database. I have preallocated the documents and they look like this

The data looks like this

{ _id : "UNIQUEKEY1:1463670000000", data: {value:NaN} }
{ _id : "UNIQUEKEY2:1463670000000", data: {value:NaN} }

I would like to query the data in the following way

{ "_id": {$regex : "/^UNIQUEKEY1.*/i"} }

I have read that you can query _id if it is a string in Brendan's comment here

I don't want the overhead of another attribute just to search by when the _id would provide me with enough


Solution

  • It's a valid setup and $regex should work fine (see https://docs.mongodb.com/manual/reference/operator/query/regex/)

    So try db.mycollection.find({ "_id": {$regex : /^UNIQUEKEY1.*/i} }) i.e. you shouldn't need the quote marks.