0

Can I have an index on subarrays?

Sample document:

{ 
    'who': [['en', 'Thomas'], ['es', 'Alfonzo'], ['de', 'Helmut']],
    'otherField': 123
}

Query:

{'who': 
    { '$elemMatch': { '1': 'Helmut'} } 
}

I need an index for this type of queries. Thanks.

2
  • 3
    Have you considered just storing the data as 'who': [ { lang: 'en', name: 'Thomas' }, ... ]? Commented May 3, 2013 at 17:37
  • Yes, but I prefer using arrays if possible. (edit: I mistakely deleted this comment from yesterday) Commented May 4, 2013 at 7:17

1 Answer 1

1

Using arrays like this isn't the best structure, because you're forcing several rather conditions on your data.

Something like this

...
"who": [{
  "language": "en", "text": "Thomas'
}, ... ]
...

EDIT: (Removed previous suggestion)

Then, as Jim Dagg pointed out, you could create an index on who.text.

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

3 Comments

If you use subdocuments inside an array like in your first code block, you can use a multikey index against who.text.
Thanks. I know I can use index if I use subdocuments instead of arrays, but I prefer using arrays if possible. If I understand the situation well, it is not possilbe to index array of arrays so I must use subdocuments.
Apologies then, but you're never really sure how much the OP knows, especially for newish technology like MongoDB. :) If it is any consolation, this is a better data structure than using nested arrays.

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.