0

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.

1 Answer 1

1

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

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

Check this example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.