1
votes

I have a mongoDBcontaining millions of documents.

I want to query the database and sort the results naturally using a specific field.

From Mongo documentation it seems that only naive sort supported. Is there a way to sort naturally?

Example:

  • doc 1 _id: "abc10.def"
  • doc 2 _id: "abc2.def"
  • doc 3 _id: "abc1.def"

Query: db_collection.find({}).sort({_id: 1})

returns a list by order:

  • doc3 ("abc1.def")
  • doc1 ("abc10.def")
  • doc2 ("abc2.def")

how can I sort to receive the following list?:

  • doc3 ("abc1.def")
  • doc2 ("abc2.def")
  • doc1 ("abc10.def")
1
@Astro: Can you give more info how to use it? I also found the mongo documentation, but wasn't able to understand how to use it.NirMH
@Astro: running your statement doesn't yield the expectedNirMH
@Astro $natural returns the documents in the order in which the database refers to them on disk. Please read the question and decide if that's really what OP needsmickl

1 Answers

1
votes

The problem here is that shorter strings should be returned before longer ones and then you should sort alphabetically strings that have the same length. To do that you need a temporary field length which can be added using $strLenBytes.

db.col.aggregate([
    {
        $addFields: {
            length: { $strLenBytes: "$_id" }
        }
    },
    {
        $sort: {
            length: 1, _id: 1
        }
    },
    {
        $project: {
            length: 0
        }
    }
])