How to make a MongoDB query sort on strings with -number postfix?

后端 未结 6 545
花落未央
花落未央 2021-01-04 01:04

I have a query:

ownUnnamedPages = Entries.find( { author : this.userId, title : {$regex: /^unnamed-/ }}, {sort: { title: 1 }}).fetch()

That

6条回答
  •  被撕碎了的回忆
    2021-01-04 01:07

    In my case we work with aggregations. The approach was to sort using the length of our string; only works when the text part is always the same (unnamed- in your case)

    db.YourCollection.aggregate([
      {
        $addFields: {
          "TitleSize": { $strLenCP: "$Title" }
        }
      },
      {
        $sort: {
          "TitleIdSize": 1,
          "Title": 1
        }
      }
    ]);
    

    Now we sort using length, the second sort will use the content.

    Example:

    • "unnamed-2", Titlesize: 9
    • "unnamed-7", Titlesize: 9
    • "unnamed-30", Titlesize: 10
    • "unnamed-1", Titlesize: 9

    The first sort will put the ids in this order: 2, 7, 1, 30. Then the second sort will put the ids in the correct order: 1, 2, 7, 30.

提交回复
热议问题