mongodbmongodb-queryaggregation-frameworkphp-mongodb

how can i apply sorting in string in mongodb


this is my sample document

{
  "string" : "class.chapter.1.topic.10"
}

how can I sort this string according to "chapter.anynumber.topic.anynumber"


Solution

  • Not exactly scientific, but here is one way:

    db.collection.aggregate([
      {
        "$project": {
          string: "$string",
          chapter_num: {
            "$toInt": {
              $arrayElemAt: [
                {
                  $split: [
                    "$string",
                    "."
                  ]
                },
                2
              ]
            }
          },
          topic_num: {
            "$toInt": {
              $arrayElemAt: [
                {
                  $split: [
                    "$string",
                    "."
                  ]
                },
                4
              ]
            }
          }
        }
      },
      {
        $sort: {
          chapter_num: 1,
          topic_num: 1
        }
      },
      {
        "$project": {
          string: "$string"
        }
      }
    ])
    

    What it does is split the string by ., then grab elements 2 and 4 as chapter_num and topic_num of the resulting array, convert them to Int and sort it with:

      {
        $sort: {
          chapter_num: 1,
          topic_num: 1
        }
      }
    

    toggle between 1 and -1 to go asc or desc.

    Note that this assumes that your string will adhere to this format: xxx.xxx.num.xxx.num.

    If used against this sample collection:

    [
      {
        "string": "class.chapter.1.topic.10"
      },
      {
        "string": "class.chapter.2.topic.3"
      },
      {
        "string": "class.chapter.1.topic.12"
      },
      {
        "string": "class.chapter.1.topic.1"
      }
    ]
    

    The result will be:

    [
      {
        "_id": ObjectId("5a934e000102030405000003"),
        "string": "class.chapter.1.topic.1"
      },
      {
        "_id": ObjectId("5a934e000102030405000000"),
        "string": "class.chapter.1.topic.10"
      },
      {
        "_id": ObjectId("5a934e000102030405000002"),
        "string": "class.chapter.1.topic.12"
      },
      {
        "_id": ObjectId("5a934e000102030405000001"),
        "string": "class.chapter.2.topic.3"
      }
    ]
    

    Playground: https://mongoplayground.net/p/6-2QRIppu0u