4

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

J.F.
  • 13,927
  • 9
  • 27
  • 65
Tyler
  • 51
  • 1
  • 6
  • http://stackoverflow.com/a/3305687/244811? – Scott Weaver May 19 '16 at 17:01
  • Any reason you are nesting your values inside a data subdocument? – Nic Cottrell May 19 '16 at 17:30
  • I am trying to preallocate the data so that it is contiguous on the storage. Here is a good video that explains it. https://www.mongodb.com/presentations/mongodb-time-series-data-part-2-analyzing-time-series-data-using-aggregation-framework – Tyler May 23 '16 at 13:00

1 Answers1

4

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.

Nic Cottrell
  • 9,401
  • 7
  • 53
  • 76
  • 2
    Are you saying this is working for _id in ObjectId type (which is the main point of this question)? Somehow it doesn't work on my _id of ObjectId type. Did I miss anything? – newman Dec 30 '20 at 16:09
  • @newman - No this $regex works only on strings. In the original question, the `_id` is of type string not ObjectId which can be perfectly fine if your application ensures that it's unique. – Nic Cottrell Jan 02 '21 at 17:26