How to Find a Document Where Any Stored URL is a Prefix of the Input URL

Hello everyone,

I’m trying to write a MongoDB query that finds documents based on whether any element in a stored array of URLs is a base path (i.e., prefix) of a given input URL.
Each document in my collection contains an array of base URLs:

{
  "configuration": {
    "urls": [
      "https://example.com",
      "https://anotherdomain.com/path"
    ]
  },
  ...
}

Currently this query implemented with strict matching, so it would be best to build on this example:

result = await this.myEntityModel
  .findOne({
    'configuration.urls': {
      $in: [payload.url],
    },
  })
  .populate('...');

Is there a way to express this kind of “reverse prefix match” (incoming value starts with any element of a stored array) directly in a MongoDB query?
Thanks in advance for your help!

  1. You can use $indexOfCP to check if the search URL starts with the base configuration URL by checking if the result is 0. ie. the configuration URL is found at index=0 of the search URL.
  2. Combine that with a $map and $anyElementTrue to get an array of True/False for when that starting index is 0.
db.collection.find({
  $expr: {
    $anyElementTrue: [
      {
        $map: {
          input: "$configuration.urls",
          in: {
            $eq: [
              {
                // your search url
                $indexOfCP: ["https://example.com/some_path", "$$this", 0]
              },
              0
            ]
          }
        }
      }
    ]
  }
})

Mongo Playground

This can also be done as a $filter with the same indexOfCP operation and then checking if the array is non-empty. (But requires an additional equality check anyway.)