Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching mongodb _id field using regex

Tags:

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

like image 927
Tyler Avatar asked May 19 '16 16:05

Tyler


People also ask

Can I use regex in MongoDB query?

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.

How do I use wildcard search in MongoDB?

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.

How do I search for a string in MongoDB?

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.


1 Answers

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.

like image 57
Nic Cottrell Avatar answered Sep 28 '22 03:09

Nic Cottrell