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
MongoDB provides the functionality to search a pattern in a string during a query by writing a regular expression. A regular expression is a generalized way to match patterns with sequences of characters. MongoDB uses Perl compatible regular expressions(PCRE) version 8.42 along with UTF-8 support.
Create a Wildcard Index on All Fields With this wildcard index, MongoDB indexes all fields for each document in the collection. If a given field is a nested document or array, the wildcard index recurses into the document/array and stores the value for all fields in the document/array.
Use the $text query operator to perform text searches on a collection with a text index. $text will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With