For example, I have a collection "test" with an index on array field "numbers", I have two documents there:
db.test.createIndex({"numbers": 1})
db.test.insert({"title": "A", "numbers": [1,4,9]})
db.test.insert({"title": "B", "numbers": [2,3,7]})
1) How can I get all results sorted by "numbers" (using index), so for each value from an array I get a full document? Like this:
{"_id": "...", "title": "A", "numbers": [1,4,9]}
{"_id": "...", "title": "B", "numbers": [2,3,7]}
{"_id": "...", "title": "B", "numbers": [2,3,7]}
{"_id": "...", "title": "A", "numbers": [1,4,9]}
{"_id": "...", "title": "B", "numbers": [2,3,7]}
{"_id": "...", "title": "A", "numbers": [1,4,9]}
2) How can I get such results (sorry for no explanation, but I think it's clear what I'm trying to achieve here):
{"_id": "...", "title": "A", "numbers": 1}
{"_id": "...", "title": "B", "numbers": 2}
{"_id": "...", "title": "B", "numbers": 3}
{"_id": "...", "title": "A", "numbers": 4}
{"_id": "...", "title": "B", "numbers": 7}
{"_id": "...", "title": "A", "numbers": 9}
3) How can I get similar results, but ordering by the second element in each array?:
{"_id": "...", "title": "B", "numbers": 3}
{"_id": "...", "title": "A", "numbers": 4}
Also I care about the performance, so it'd be great if you explain which technique is faster / slower (if there is more than one way to do it, of course). Thanks.
UPD: Let me clarify. We have an index on "numbers" array. So I want to iterate this index from min to max values and get a document which the current value belongs. So some document will be presented in results N times, where N = number of elements in its array ("numbers" in this case).