MongoDB query to sort by words

To sort by words in a custom order in MongoDB, use $addFields with $cond to assign priority values to specific words, then sort by those values.

Syntax

db.collection.aggregate([
    {
        $addFields: {
            sortByWords: {
                $cond: [
                    { $eq: ["$fieldName", "firstPriorityValue"] },
                    0,
                    { $cond: [{ $eq: ["$fieldName", "secondPriorityValue"] }, 1, 2] }
                ]
            }
        }
    },
    {
        $sort: {
            sortByWords: 1
        }
    }
]);

Sample Data

db.demo62.insertMany([
    {"Subject": "MySQL"},
    {"Subject": "MongoDB"},
    {"Subject": "Java"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e287084cfb11e5c34d8992f"),
        ObjectId("5e287085cfb11e5c34d89930"),
        ObjectId("5e287086cfb11e5c34d89931")
    ]
}

Display all documents from the collection ?

db.demo62.find();
{ "_id": ObjectId("5e287084cfb11e5c34d8992f"), "Subject": "MySQL" }
{ "_id": ObjectId("5e287085cfb11e5c34d89930"), "Subject": "MongoDB" }
{ "_id": ObjectId("5e287086cfb11e5c34d89931"), "Subject": "Java" }

Example: Custom Word Priority Sort

Sort documents with MongoDB first, MySQL second, and Java last ?

db.demo62.aggregate([
    {
        $addFields: {
            sortByWords: {
                $cond: [
                    { $eq: ["$Subject", "MongoDB"] },
                    0,
                    { $cond: [{ $eq: ["$Subject", "MySQL"] }, 1, 2] }
                ]
            }
        }
    },
    {
        $sort: {
            sortByWords: 1
        }
    }
]);
{ "_id": ObjectId("5e287085cfb11e5c34d89930"), "Subject": "MongoDB", "sortByWords": 0 }
{ "_id": ObjectId("5e287084cfb11e5c34d8992f"), "Subject": "MySQL", "sortByWords": 1 }
{ "_id": ObjectId("5e287086cfb11e5c34d89931"), "Subject": "Java", "sortByWords": 2 }

How It Works

  • $addFields creates a temporary field sortByWords with priority values
  • $cond assigns 0 to "MongoDB", 1 to "MySQL", and 2 to all other values
  • $sort orders documents by the priority values in ascending order

Conclusion

Use $addFields with nested $cond operators to create custom word-based sorting priorities. This approach allows you to define specific ordering rules for text values that don't follow alphabetical order.

Updated on: 2026-03-15T02:52:16+05:30

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements