I am trying to sort arrays in MongoDB shell.
This seems to be the only syntax available to use.
db.products.updateOne({"name": "ben"}, {$push: {"hobbies": {$each: [], $sort: -1}}})
My question is that, is there no other way to do this – in MongoDB, do I have to use th $push operator – as I am not doing a push operation.
2
Answers
I don’t understand your antipathy against aggregation pipelines, it would be a simple
As per requested, you can provide the empty array in the
$push
operator to perform sorting the element in the array.When your elements in the array to be sorted are non-documents, you provide the sorting order as below:
Demo (Sorting non-documents in array) @ Mongo Playground
When your elements in the array to be sorted are documents, you need to provide the field used to sort and the sorting order as below:
Demo (Sorting documents in array) @ Mongo Playground