I am using grails(2.3.7) mongodb gorm plugin mongodb:3.0.1. I have following collection in db
{
"_id" : ObjectId("567eac392c56fd49950e2441"),
"comments" : [
{
"commentText" : "test comments!",
"userId" : "patient@gmail.com",
"likes" : 10,
"date" : "2015-12-25T10:34:53.048Z"
},
{
"commentText" : "master piece",
"userId" : "patient@gmail.com",
"likes" : 12,
"date" : "2015-12-25T10:34:53.052Z"
},
{
"commentText" : "test comments!",
"userId" : "patient@gmail.com",
"likes" : 10,
"date" : "2015-12-25T10:34:53.048Z"
},
{
"commentText" : "master piece",
"userId" : "patient@gmail.com",
"likes" : 12,
"date" : "2015-12-25T10:34:53.052Z"
}
],
"doctorUserId" : "doctor2@gmail.com",
"recommendation" : 0,
"version" : NumberLong(2)
}
Now I want to query inside comments parameter order by date (inside comment) using mongoDB gorm
Thanks inadvance
First of all, for correct sorting by date all your date fields need to have Date type not string. So your date field should look like this:
date: ISODate("2015-12-26T16:33:44.592Z")
You can sort nested array using mongodb aggregation. Try the following code:
db.collection.aggregate([
{$unwind: "$comments"},
{$sort: {'comments.date': 1} },
{$group: {
_id: '$_id',
comments: {$push: '$comments'},
version: {$first: "$version"},
doctorUserId: {$first: "$doctorUserId"},
recommendation: {$first: "$recommendation"}
}
}
])