Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongo Aggregation Query – Filter Condition where string contains value

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading