Luís Soares
Luís Soares

Reputation: 6202

Query MongoDB with a regex expression against an ObjectId

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).

Upvotes: 11

Views: 9184

Answers (5)

jamix
jamix

Reputation: 5628

You can use $where as mentioned here:

.find({"$where": "/004/.test(this._id.str)"})

Upvotes: 1

Farrukh Malik
Farrukh Malik

Reputation: 796

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.

Upvotes: 6

Derese Getachew
Derese Getachew

Reputation: 460

I believe this is one of the areas where mongodb is lacking; and also the team @ mongodb looks like they won't support this feature as this (https://jira.mongodb.org/browse/SERVER-1146) jira issue indicates. The argument seems to be to use our own id that is of string format but objectIds make sense in big systems where you have large volumes of transactions e.g. Amazons order numbers

The Solution I cam up with is as follows:

I created another column that copies the first six digits of my _id field and is of string type . The reason I choose the first 6 digits of my _id field are; one to save space and be compact and also at the end of the day the reason I need a regex expression is for searching purpose and that fits well for my needs.

Upvotes: 1

nickmilon
nickmilon

Reputation: 1372

  • 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.

Upvotes: 5

Brian Stephens
Brian Stephens

Reputation: 5261

This is what you need:

db.artigo.find( { _id : { $regex: '004' } } )

Upvotes: -4

Related Questions