I have documents in MongoDB which look like this
{
"_id": "...",
"ranks":[
{"pos": 1,"type":"some type"},
{"pos": 56,"type":"other type"},
...
]
}
I want to find all items where ‘ranks.type’ matches “some type” and sort them by ‘pos’ in this embedded document.
In SQL I would do something like this (tables document and document_rank)
SELECT
D.*
FROM
document D
JOIN
document_rank DR ON DR.document_id = D.id
WHERE
DR.type="some type"
ORDER BY
DR.pos
I’m just asking if I can do this by embedding ranks or I have to link them to document. My experiments show that I have to link.
You are getting back a single document, so it doesn’t make sense to ask about sorting – there is no concept of sorting embedded elements in an array within a single document.
However, starting in 2.1 (development version) the aggregation framework lets you do what you want by letting you select documents,
$unwindthe array, and then sort the resultant documents (you can even change the general shape of the result if needed using$project).Note that these are not your full original documents, they are documents with only one “ranks” embedded element each, that’s why they can be sorted on the embedded field now.
If this sort of operation is integral to your application, then the schema design you have may not be the best choice. I would suggest looking at the types of queries and access patterns your application will have with these objects, in case changing the schema would simplify things significantly.