Home > Software engineering >  Mongo Aggregation Query - Filter Condition where string contains value
Mongo Aggregation Query - Filter Condition where string contains value

Time:09-14

I have a mongo query filtering input from "notes". Notes is an array of objects containing the fields user, date, and comment. This is the schema of the notes array:

notes: [ { comment: { type: String }, user: { type: String }, date: { type: Date }}]

I'm successfully using $addFields with $filter to remove comments from an admin user. I'm also wanting to ensure comments contain a string "m]". It seems like I'm unable to use a regular expression. Anyone know a way to approach this?

{
    $addFields: {
        notes: {
            $filter: {
                input: '$notes',
                as: 'note',
                cond: { $and: [ 
                      { $ne: ['$$note.user', 'admin'] },
                      { $eq: ['$$note.comment', /.*m].*/i ] }, 
                    ]
                }
            }
        }
    }
},

I'm currently running Mongo v4.0.28 so $regexMatch does not appear to be an option.

I have created a Mongo Playground to better illustrate the issue: https://mongoplayground.net/p/uyOVhIXSFQf

CodePudding user response:

You can use $indexOfBytes instead of $eq:

[{
  $addFields: {
    notes: {
      $filter: {
        input: "$notes",
        as: "note",
        cond: {
          $and: [{
              $ne: [
                "$$note.user",
                "admin"
              ]
            },
            {
              $ne: [
                -1,
                {
                  $indexOfBytes: [
                    "$$note.comment",
                    "m"
                  ]
                }
              ]
            }
          ]
        }
      }
    }
  }
}]

Updated MongoDB Playground.

  • Related