Grails mongodb gorm 条件查询

Grails mongodb gorm criteria query

我正在使用 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

按日期(内部评论)查询内部评论参数

提前致谢

首先,为了按日期正确排序,所有日期字段都需要 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"}
        }
    }
]) 

将 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
}

注意:以上内容未经测试,因此可能需要进行一些调整,但聚合的类似使用在我的应用中效果很好。