How to specify the order in which the query returns matching documents in MongoDB

MongoDBDatabaseBig Data Analytics

To specify the order in which the query returns matching documents, use cursor.sort() in MongoDB. The cursor is db.collectionName.find().

Let us create a collection with documents −

> db.demo259.insertOne({"Subject":"MySQL"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e47ae1f1627c0c63e7dba98")
}
> db.demo259.insertOne({"Subject":"Java"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e47ae231627c0c63e7dba99")
}
> db.demo259.insertOne({"Subject":"MongoDB"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e47ae281627c0c63e7dba9a")
}

Display all documents from a collection with the help of find() method −

> db.demo259.find();

This will produce the following output −

{ "_id" : ObjectId("5e47ae1f1627c0c63e7dba98"), "Subject" : "MySQL" }
{ "_id" : ObjectId("5e47ae231627c0c63e7dba99"), "Subject" : "Java" }
{ "_id" : ObjectId("5e47ae281627c0c63e7dba9a"), "Subject" : "MongoDB" }

Following is the query to sort with a specific order −

> db.demo259.find().sort({"Subject":1});

This will produce the following output −

{ "_id" : ObjectId("5e47ae231627c0c63e7dba99"), "Subject" : "Java" }
{ "_id" : ObjectId("5e47ae281627c0c63e7dba9a"), "Subject" : "MongoDB" }
{ "_id" : ObjectId("5e47ae1f1627c0c63e7dba98"), "Subject" : "MySQL" }
raja
Published on 31-Mar-2020 08:20:17
Advertisements