MongoDB query to sort by words

MongoDBDatabaseBig Data Analytics

To sort by words, use $addField along with $cond. Let us create a collection with documents −

> db.demo62.insertOne({"Subject":"MySQL"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e287084cfb11e5c34d8992f")
}
> db.demo62.insertOne({"Subject":"MongoDB"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e287085cfb11e5c34d89930")
}
> db.demo62.insertOne({"Subject":"Java"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e287086cfb11e5c34d89931")
}

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

> db.demo62.find();

This will produce the following output −

{ "_id" : ObjectId("5e287084cfb11e5c34d8992f"), "Subject" : "MySQL" }
{ "_id" : ObjectId("5e287085cfb11e5c34d89930"), "Subject" : "MongoDB" }
{ "_id" : ObjectId("5e287086cfb11e5c34d89931"), "Subject" : "Java" }

Following is the query to sort by words −

> db.demo62.aggregate([
...    {
...       $addFields: {
...          sortByWords: {
...             $cond: [
...                { $eq: ["$Subject", "MongoDB"] },
...                0,
...                { $cond: [{ $eq: ["$Subject", "MySQL"] }, 1, 2] }
...             ]
...          }
...       }
...    },
...
...    {
...       $sort: {
...          sortByWords: 1
...       }
...    }
... ]);

This will produce the following output −

{ "_id" : ObjectId("5e287085cfb11e5c34d89930"), "Subject" : "MongoDB", "sortByWords" : 0 }
{ "_id" : ObjectId("5e287084cfb11e5c34d8992f"), "Subject" : "MySQL", "sortByWords" : 1 }
{ "_id" : ObjectId("5e287086cfb11e5c34d89931"), "Subject" : "Java", "sortByWords" : 2 }
raja
Published on 03-Apr-2020 12:46:37
Advertisements