How do you order the results of projections in a Grails criteria when using MongoDB?
It seems that sorting is ignored by MongoDB. The code below correctly returns a list of sorted book titles when run with the Grails default in-memory HSQLDB database. Switching over to MongoDB causes the sorting to be ignored.
BookController.groovy
class BookController {
def library = [
[author: "Jan", title: "HTML5"],
[author: "Lee", title: "CSS3"],
[author: "Sue", title: "JavaScript"]
]
def titles() {
library.each { if (!Book.findByTitle(it.title)) new Book(it).save() }
def ids = Book.createCriteria().list() {
projections { id() }
order "title"
}
def titles = ids.collect { Book.get(it).title }
render titles as JSON
}
}
Result with default DB (correct):
["CSS3","HTML5","JavaScript"]
Result with MongoDB (wrong):
["HTML5","CSS3","JavaScript"]
Note that the above book example is just some trivial code to illustrate the problem. The real goal is to generate a list of domain IDs sorted by a field of the domain so that the domain can be iterated over in the desired order.
The actual domain I'm dealing with is too large to fit in memory. In other words, this would crash the application: Book.list().title.sort()
Below is additional background information.
Book.groovy
class Book {
String title
String author
static mapWith = "mongo"
}
BuildConfig.groovy
...
compile ":mongodb:1.3.1"
...
DataSource.groovy
...
grails {
mongo {
host = "localhost"
port = 27017
databaseName = "book-store"
}
}
The projections support has been rewritten to use the MongoDb aggregation framework in 3.0 of the plugin. So the example where should work in 3.0 with or without ordering. See https://jira.grails.org/browse/GPMONGODB-305
Relevant commit https://github.com/grails/grails-data-mapping/commit/1d1155d8a9e29a25413effce081c21a36629137d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With