我如何在 mongodb 中应用字符串排序

问题描述

这是我的示例文档

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

如何根据“chapter.anynumber.topic.anynumber”对这个字符串进行排序

解决方法

不完全科学,但这是一种方法:

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"
    }
  }
])

它的作用是用 . 分割字符串,然后获取元素 2 和 4 作为结果数组的 chapter_numtopic_num,将它们转换为 Int 并使用以下命令对其进行排序:

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

1-1 之间切换以上升或下降。

请注意,这假定您的字符串将遵循以下格式:xxx.xxx.num.xxx.num

如果用于此示例集合:

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

结果将是:

[
  {
    "_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"
  }
]

游乐场:https://mongoplayground.net/p/6-2QRIppu0u