Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: query against value in nested array?

Tags:

arrays

mongodb

I have documents with such kind of schema:

{
   ...
  "coverages" : [
    [
      "GB",
      "WC1"
    ],
    [
      "GB",
      "SE2"
    ],
    ...
  ]
}

I want to find all documents where 'coverages' contains an array second element of which starts with 'WC', i.e. coverages matches with ['GB', /^WC/].

Is there any way to do it with standard mongodb query language?

I guess it could be easily done with custom JavaScript function, but docs says it's much slower...

Thanks!

P.S. I'd like to avoid changing the schema.

update: there is relates bug/misfeture in Mongo: https://jira.mongodb.org/browse/SERVER-1264

like image 695
Alexander Avatar asked Jun 28 '26 13:06

Alexander


1 Answers

I guess this should work:

db.mycollection.find({"coverages": {"$elemMatch": {"2": /^WC/}}})
like image 80
Ninja Avatar answered Jun 30 '26 15:06

Ninja