1

MongoDB provides a very useful $sort modifier to use with the $push operation, but unfortunately it looks like I can only ask it to sort my elements by a named key - which I don't have.
Another option that could be the alternative is the sort function: sort({'array.0': 1})source, but what if I have an array inside an array?

My documents structure in the collection is as follows:

{
"_id" : 123456,
"v" : [ 
    [ 
        some id, 
        some score
    ], 
    [ 
        "456456", 
        1.5
    ], 
    [ 
        "654645", 
        43
    ],
    ...
]
}

And I want to sort the v array by the score (second element) of each child array.

So using $sort: I can't use a key name

'$push': {
    'v': {
        '$each': [[id, score]],
        '$sort': {???: -1},
    }
}

and using sort(): I can't use an array of array:

sort({'v.???.0': -1})

Is there something I'm missing, or is there another way to do this kind of sorting without fetching the document, sorting, and replacing? That would be a very time-consuming opeartion. Thanks!

2
  • 2
    Fair enough question, but you really cannot do it. You can { $sort: -1 } which would order on the values of the "first" element. But for the "second" you would be better off using the same "k" and "v" structure with objects instead. Then you can $sort: { v: -1 } on the value. But there is no notation for the current form. Difficult to query like that as well. Commented Jul 13, 2017 at 8:18
  • @NeilLunn Thanks! I decided to change the sub-array to a document and give names to each field (id, score). For my database that will take a few hours to complete, but it's my best bet. Commented Jul 13, 2017 at 14:17

0

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.