3

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

2
  • Are you aware that the coverages key contains a list of lists? Just want to make sure you are doing that on purpose. Commented Dec 27, 2011 at 16:21
  • My bad, I was lazy and didn't mentioned that coverages is long list of pairs =\ Commented Dec 28, 2011 at 15:48

2 Answers 2

5

I guess this should work:

db.mycollection.find({"coverages": {"$elemMatch": {"2": /^WC/}}})
Sign up to request clarification or add additional context in comments.

4 Comments

Just noticed that you have given "coverages" as an array of arrays. Is that a typo or is that how it is? If that is how your schema is defined, then change query to "coverages.0.1"
Yes, actually it's long array of arrays (pairs). And I want to find out if it's possible to query it without changing the schema, that's what this question is about :)
I've edited the code based on the edited example you have added
what "2" means in the query? Is it interpreted as position in array?
0

db.collection.find({ "coverages.0.1": /^WC/ }) should do the trick. It is saying, match documents where the second element of the first array in the key coverages starts with WC.

However, this is a bad schema if you are trying to associate GB (the first item in the array) with the second item in the array.

This is a natural case for the document/object/dictionary which maps keys to values.

Make it like this:

{
  "coverages" : { "GB": "WC1" }
}

Now your query much more naturally matches your logic: db.collection.find({ "coverages.gb": /^WC/ })

1 Comment

I've edited example: coverages contains much more than one element, so I guess your approach woudn't work :( I believe natural mongo schema for this case should look like "coverages": [{"country": "GB", "region": "WC1"}, ...].

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.