I’ve got a associative container (with the semantics of a c++ map) serialized in a mongo db array. In my collection I retrieve arrays which contain my key as so.
db.qrs.find( { "u.i" : 111892 })
I would like to sort on the “value” element of my “map”. Such as :
db.qrs.find( { "u.i" : 731612 }).sort( { "u.c" : -1} )
However this just sorts the array within the document, rather then sorting per row in the result set. An example sorted row:
{ "_id" : ObjectId("4f2f9acea2b3adfce39ae395"), "i" : 11, "r" : 1,
"s" : ")n(kQ!$A=@%RPv-SB0dQXh7ME*%lw=!$@(VshFU1H6#b7r*wb()t3Ps!^xQ1rNr7j", "u" :
[ { "c" : 7, "i" : 29518, "p" : 0 }, { "c" : 1, "i" :
924577, "p" : 3 }, { "c" : 1, "i" : 731612, "p" : 1 } ] }
I had some hope that the position operator might work, alas it does not do what I expected it to , my query was formulated as:
db.qrs.find( { "u.i" : 111892 }).sort( { "u.$.c" : -1} )
So, how does my desired query look like ?
Can I somehow transpose the result set to hoist the key-value pair matching my predicate to become part of the top-level document structure of the result set ?
MongoDB never sorts the array itself. You’re seeing the array as it exists in the document.
Your specific use case is not supported by MongoDB at this time. You cannot match a specific element in the query and then sort on that element alone.
You can only fix this by avoiding the use of an array, for example by using the value for “i” as the key of the embedded element :
You can then sort through
Obviously this solution may not be available to you but I don’t see any other routes that do not involve putting your array elements in a dedicated collection (which is a better schema decision in my opinion).