-3

我正在使用grails(2.3.7) mongodb gorm插件mongodb:3.0.1。 我在数据库中有以下集合

 {
        "_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 按日期(内部注释)查询内部注释参数顺序

提前致谢

4

2 回答 2

0

首先,要按日期正确排序,所有日期字段都需要日期类型而不是字符串。因此,您的日期字段应如下所示:

date: ISODate("2015-12-26T16:33:44.592Z")

您可以使用 mongodb聚合对嵌套数组进行排序。试试下面的代码:

db.collection.aggregate([
    {$unwind: "$comments"}, 
    {$sort: {'comments.date': 1} }, 
    {$group: {
        _id: '$_id', 
        comments: {$push: '$comments'}, 
        version: {$first: "$version"}, 
        doctorUserId: {$first: "$doctorUserId"},
        recommendation: {$first: "$recommendation"}
        }
    }
]) 
于 2015-12-26T16:30:54.127 回答
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
}

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

于 2016-02-26T17:45:52.543 回答