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

后端 未结 6 546
花落未央
花落未央 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:06

    If you 0 pad the numbers you will be able to search as a string in the right order, so instead of 0,1,2,3,4,5,6,7,8,9,10,11... use 01,02,03,04,05,06,07,08,09,10,11... and a string search will return them in order.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-04 01:13

    In mongo is not possible (sort strings in ascii) but you can sort with the below function after you get all documents from the collection

    const sortString = (a, b) => {
      const AA = a.title.split('-');
      const BB = b.title.split('-');
    
      if (parseInt(AA[1], 10) === parseInt(BB[1], 10)) {
        return 0;
      }
      return (parseInt(AA[1], 10) < parseInt(BB[1], 10)) ? -1 : 1;
    };
    
    document.sort(sortString);
    
    0 讨论(0)
  • 2021-01-04 01:15

    The mongo documentation said you can use Collation for this goal as @Eugene Kaurov said you can use

    .collation({locale: "en_US", numericOrdering: true})
    

    this is the official documentation: mongo ref

    and be aware that the accepted answer is not correct now

    0 讨论(0)
  • 2021-01-04 01:28

    You can use

    db.collectionName.find().sort({title: 1}).collation({locale: "en_US", numericOrdering: true})
    

    numericOrdering flag is boolean and is Optional. Flag that determines whether to compare numeric strings as numbers or as strings. If true, compare as numbers; i.e. "10" is greater than "2". If false, compare as strings; i.e. "10" is less than "2". Default is false.

    0 讨论(0)
  • 2021-01-04 01:29

    MongoDB can't sort by numbers stored as strings. You either have to store the number as an integer in its own field, pad with leading zeroes, or sort the results after they've been returned from the database.

    0 讨论(0)
提交回复
热议问题