Home > Net >  MongoDB: Aggregate on array elements with regex
MongoDB: Aggregate on array elements with regex

Time:12-16

I use MongoDB v 4.2.17 where I have a collection of documents such as this:

[
  {
    a: 'a',
    b: 'b',
    c: ['apples', 'grapes']
  },
  {
    a: 'a',
    b: 'b',
    c: ['elephants', 'apes']
  }
]

I need to write a query that will return all documents, where any element of array c matches a regex provided.

I have a solution that matches the first element in the array:

db.collection.aggregate([{$match: {'c.0': {$regex: 'apes'} }}])

This query successfully matches documents where the first element in the array matches the regex.

I need to write an aggregation that would get the documents where any element in the array matches the regex.

I've tried this (didn't work)

db.collection.aggregate([{$match: {'c.$': {$regex: 'apes'} }}])

I need to use a regex and an aggregation, so a simple find won't work. Thanks in advance.

CodePudding user response:

Simply use the value c, not c.0 nor c.$.

db.collection.aggregate([
  {
    $match: {
      "c": {
        $regex: "apes"
      }
    }
  }
])

Check this example

  • Related