Mongodb sort query

In MongoDB, we can manually sort the documents in a collection in the selected database using db.collection_name.find().sort() method.

  • Type the command collection_name.find() in the command prompt to see all the inserted document in a collection.

For Example: db.HELLO.find()

  • Type the command collection_name.find().sort({KEY: 1}) in the command prompt to sort all the inserted documents in a collection in an ascending order (according to the specified field of the document).

For Example: db.HELLO.find().sort({“database_types”: 1})

  • Type the command collection_name.find().sort({KEY: -1}) in the command prompt to sort all the inserted documents in a collection in the descending order (according to the specified field of the document).

For Example: db.HELLO.find().sort({“database_types”: -1})

Please follow and like us:
Content Protection by DMCA.com