Home > database >  MongoDB: Query ObjectId via Substring
MongoDB: Query ObjectId via Substring

Time:06-09

I want to be able to query the _id field via a substring in my MongoDB collection. However since the ObjectId is it's own object and not a pure string this is difficult. This is the Query I'm currently using to no avail, but hopefully it gives more clarity on what I'm trying to accomplish.

{_id: {$regex: '62a0ed7'}}

Many thanks!

CodePudding user response:

You can not query with a regex expression operator against a field that contains ObjectId's.

I suggest providing your own unique string as _id then you can use a regex the expression for querying.

Example:

    // This will add a tempUserId property to each document
    Model.aggregate([
      {
        $addFields: {
          tempUserId: { $toString: '$_id' },
        }
      },
      {
        $match: {
          tempUserId: { $regex: '62a0ed7', $options: "i" }
        }
      }
    ]);

A faster solution is that you can also add a pre create hook or whatever to save an id (other than the _id) containing the value of the ObjectId (_id) as a string and you can make a text index on it and do search instead of regex.

  • Related