- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to sort by words
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 }
Advertisements