skip to Main Content

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


  1. I don’t understand your antipathy against aggregation pipelines, it would be a simple

    db.products.updateOne(
       { name: "ben" },
       [{ $set: { hobbies: { $sortArray: { input: "$hobbies", sortBy: -1 } } } }]
    )
    
    Login or Signup to reply.
  2. As per requested, you can provide the empty array in the $push operator to perform sorting the element in the array.

    To use the $sort modifier, it must appear with the $each modifier. You can pass an empty array [] to the $each modifier such that only the $sort modifier has an effect.

    When your elements in the array to be sorted are non-documents, you provide the sorting order as below:

    {
      hobbies: ["dancing", "jogging"]
    }
    
    db.products.updateOne({"name": "ben"}, 
        {$push: {"hobbies": {$each: [], $sort: -1}}})
    

    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:

    {
      hobbies: [
        { name: "dancing" }, 
        { name: "jogging" }
      ]
    }
    
    db.products.updateOne({"name": "ben"}, 
        {$push: {"hobbies": {$each: [], $sort: { name: -1 }}}})
    

    Demo (Sorting documents in array) @ Mongo Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search