'How to sort records based on the value that is inside an object in MongoDb

Consider the following MongoDB Collection

[
    {
        _id: 123123,
        name: "abc"
        topic: {
            asda: "Z"
        }
    },
    {
        _id: 123123,
        name: "abc"
        topic: {
            dasd: "P"
        }
    },{
        _id: 123123,
        name: "abc"
        topic: {
            qwer: "A"
        }
    }
]

After performing a query need records sorted(case-insensitively) based on the value inside the topic object.

Note: The key inside the topic object will be always a different and unique string for every record

So the result records should be as follows

[
    {
        _id: 123123,
        name: "abc"
        topic: {
            qwer: "A"
        }
    },
    {
        _id: 123123,
        name: "abc"
        topic: {
            dasd: "P"
        }
    },{
        _id: 123123,
        name: "abc"
        topic: {
            qwer: "Z"
        }
    }
]

Thanks in Advance :)



Solution 1:[1]

If you want to get the results sorted by the value of an unknown key, you can use $objectToArray

db.collection.aggregate([
  {
    $addFields: {
      topicArr: {
        $objectToArray: "$topic"
      }
    }
  },
  {
    $sort: {
      "topicArr.v": 1
    }
  },
  {
    $unset: "topicArr"
  }
])

As you can see on this playground example

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1