Home > Enterprise >  mongodb: match documents without substring in array field
mongodb: match documents without substring in array field

Time:04-09

I'm trying to match documents without a substring in an array field, in an aggregation pipeline.

I believe I need to add a field and then do a $match on -1, but I'm stuck on $indexOfBytes to find substrings in an array field.

db.collectionName.aggregate([{$addFields:{indexOfA:{$indexOfBytes:['$arrayName.fieldName1.fieldName2','A']}}}])

I get the error:

MongoServerError: PlanExecutor error during aggregation :: caused by :: $indexOfBytes requires a string as the first argument, found: array

collection example:

[
  { arrayName: [ fieldName1: { fieldName2: 'A' } ] },
  { arrayName: [ fieldName1: { fieldName2: 'B' } ] },
  { arrayName: [ fieldName1: { fieldName2: 'C' } ] },
  { arrayName: [ ] }
]

desired result (:

[
  { arrayName: [ fieldName1: { fieldName2: 'B' } ] },
  { arrayName: [ fieldName1: { fieldName2: 'C' } ] },
  { arrayName: [ ] }
]

CodePudding user response:

Maybe something like this:

db.collection.aggregate([
{
 $addFields: {
  arrayName: {
    "$filter": {
      "input": "$arrayName",
      "as": "a",
      "cond": {
        $eq: [
          {
            $indexOfBytes: [
              "$$a.fieldName1.fieldName2",
              "A"
            ]
          },
          -1
        ]
      }
     }
    }
   }
  },
  {
   $match: {
    $expr: {
     $ne: [
       {
         $size: "$arrayName"
       },
       0
     ]
    }
   }
  }
 ])

Explained:

  1. $filter arrayName elements not having A in fieldName2
  2. $match only the non-empty arrayName arrays

playground

  • Related