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

how can i apply sorting in string in 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