Home > Blockchain >  Getting the position of specific words in documents in mongoDB
Getting the position of specific words in documents in mongoDB

Time:11-27

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

CodePudding user response:

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

  • Related