0

I’m using $indexOfCP for locating the index of some specific words. Unfortunately, it only returns the first result. I want all the occurrences. Plus, $indexOfCP is case sensitive and I want it to be case-insensitive.

here is an example:

db.inventory.aggregate(
   [
     {
       $project:
          {
            cpLocation: { $indexOfCP: [ "$item", "foo" ] },
          }
      }
   ]
)

{ $indexOfCP: [ "cafeteria", "e" ] } result: 3

  • 1
    You can use the `$regexFindAll` aggregate operator to find the indexes of all occurrences of a sub-string, in a case-insensitive manner. – prasad_ Nov 26 '21 at 14:07

1 Answers1

1

You can use $regexFindAll which returns an array with the indexes in the key idx. So you can add an stage to get cpLocation.idx like this:

Also adding "options": "i" the regex is case insensitive.

db.collection.aggregate([
  {
    $project: {
      cpLocation: {
        "$regexFindAll": {
          "input": "$item",
          "regex": "e",
          "options": "i"
        }
      },
      
    }
  },
  {
    "$addFields": {
      cpLocation: "$cpLocation.idx"
    }
  }
])

Example here

J.F.
  • 13,927
  • 9
  • 27
  • 65