我正在使用 grails(2.3.7) mongodb gorm 插件 mongodb:3.0.1。 我在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)
}
现在我想使用mongoDB gorm
按日期(内部注释)查询内部注释参数非常感谢
答案 0 :(得分:0)
首先,为了按日期正确排序,所有日期字段都需要Date type不是字符串。所以你的日期字段应如下所示:
date: ISODate("2015-12-26T16:33:44.592Z")
您可以使用mongodb aggregation对嵌套数组进行排序。请尝试以下代码:
db.collection.aggregate([
{$unwind: "$comments"},
{$sort: {'comments.date': 1} },
{$group: {
_id: '$_id',
comments: {$push: '$comments'},
version: {$first: "$version"},
doctorUserId: {$first: "$doctorUserId"},
recommendation: {$first: "$recommendation"}
}
}
])
答案 1 :(得分:0)
转换Volodymyr Synytskyi对Grails / GORM的回答:
DBObject unwind = new BasicDBObject(['$unwind': '$comments']);
DBObject sort = new BasicDBObject(['$sort': [
'comments.date' : 1
]]);
DBObject group = new BasicDBObject(['$group': [
'_id' : '$_id',
'comments' : ['$push' : '$comments'],
'version' : ['$first': '$version'],
'doctorUserId' : ['$first': '$doctorUserId'],
'recommendation': ['$first': '$recommendation']
]]);
DBColleciton collection = DoctorSocial.collection;
AggregationOutput aggregationOutput = collection.aggregate([unwind, sort, group]);
aggregationOutput.results().each { dbObject ->
// Do something with your results
}
注意:以上内容未经测试,因此可能会进行一些调整,但类似的聚合使用在我的应用程序中运行良好。