Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query MongoDB with a regex expression against an ObjectId

Tags:

regex

mongodb

Is it possible to do a query like:

db.artigo.find( { _id : ObjectId('520a504a3004bc615fcfcf16') } )

but using a regex on ObjectId?

For example, do get _ids that contains "004" on that position above.

PS. The reason is to implement a shorty service based on some fields, namely the _id. I'm trying to create an implicit "shorty" service instead of an explicit one (with a field generated for the purpose).

like image 607
Luís Soares Avatar asked Apr 10 '15 18:04

Luís Soares


People also ask

Can I use regex in MongoDB query?

MongoDB uses Perl compatible regular expressions(PCRE) version 8.42 along with UTF-8 support. In MongoDB, we can do pattern matching in two different ways: With $regex Operator. Without $regex Operator.

What is ObjectId type in MongoDB?

An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running. The next 2 bytes are of process id. The last Field is 3 bytes used for increment the objectid.

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.


2 Answers

  • ObjectId is not a string but a special type in MongoDB. You can not
    query with a regex expression operator against a field that contains ObjectId's.
  • But... _id doesn't have to be an ObjectId, so what i would suggest is providing your own unique string as _id then you can use a regex
    expression for querying.
like image 148
nickmilon Avatar answered Oct 20 '22 05:10

nickmilon


ObjectId is not a string but a special type in MongoDB. You can not query with a regex expression operator against a field that contains ObjectId's.

_id doesn't have to be an ObjectId, so what I would suggest is providing your own unique string as _id then you can use a regex the expression for querying.

Example:

let userId = 'bf44fa';

const result = await Users.aggregate([
  {
    $addFields: {
      tempUserId: { $toString: '$_id' },
    }
  },
  {
    $match: {
      tempUserId: { $regex: userId, $options: "i" }
    }
  }
]).exec();

Now we can find by _id with the last 6 digits or start 6 digits by using aggregation as your wish.

like image 30
Farrukh Malik Avatar answered Oct 20 '22 04:10

Farrukh Malik