Previously, in CBL 3.0, as well as in 3.1 when querying the default collection, documents are sorted by document ID numerically in query results. But when querying just the document IDs in a non-default collection in 3.1, the results are sorted by ID using a non-numeric string sort. For example:
val db = Database("test")
val col = db.createCollection("collection")
for (i in 1..20) {
db.defaultCollection?.save(MutableDocument(i.toString()))
col.save(MutableDocument(i.toString()))
}
db.createQuery("SELECT META().id FROM ${db.defaultCollection?.fullName}")
.execute()
.use { rs -> println("_default: " + rs.map { it.getString("id") }) }
db.createQuery("SELECT META().id FROM ${col.fullName}")
.execute()
.use { rs -> println("collection: " + rs.map { it.getString("id") }) }
will output:
_default: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
collection: [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 3, 4, 5, 6, 7, 8, 9]
Interestingly, if you add something else to the query SELECT
, the sort works correctly numerically. E.g. changing SELECT META().id
to SELECT META().id, *
outputs:
_default: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
collection: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
The same occurs with document IDs that contain numbers, e.g. âdoc-1â, âdoc-2â, âdoc-3â, etc.
UPDATE:
After further testing, I realized itâs not that itâs doing a numeric sort by document ID, but just returning the documents in their insertion order, while non-default collections when selecting only META().id
are performing an additional string sort by document ID for some reason.