Home > database >  How to sort records based on the value that is inside an object in MongoDb
How to sort records based on the value that is inside an object in MongoDb

Time:04-28

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 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 :)

CodePudding user response:

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

  • Related