Mongodb:如何按对象列表分组

时间:2017-03-21 08:50:26

标签: mongodb grails groovy gorm

我有一个下面的学生集合,其中包含List可选,并按列表聚合集合组。

   {
    "_id" : "57e3e55c638cb8b971",
    "firstName" : "St1_firstName",
    "lastName" : "St1_lastName",
    "email" : "St1_firstname.lastName@xxx.com",
    "subjects" : [
        {
            "_id" : "35a344d888dd8b363",
            "code" : "00 00 00",
            "name" : "subject1"
        },
        {
            "_id" : "23a344d888dd8b335",
            "code" : "01 00 00",
            "name" : "subject2"
        },
        {
            "_id" : "45a344d888dd8b987",
            "code" : "01 01 00",
            "name" : "subject3"
        }
    ],
    "category" : {
        "_id" : "76a344d888dd8b887",
        "label" : "label"
    },
    "classroom" : {
        "_id" : "5877df01937e1f97942c9e06"
    }
}

以下是用于按列表汇总集合的GORM代码段

DBObject unwind =  new BasicDBObject('_id',new BasicDBObject('$unwind','$subjects'))
        unwind.append('subjects','$subjects.code')
        unwind.append('count', new BasicDBObject('$sum', 1))
        DBObject group = new BasicDBObject('$group', unwind)
        queryPipe << group

这不起作用,你能否更正代码

当我尝试使用以下完整代码时获取NullPointerException

List queryPipe = []
        DBObject matchclassroom = new BasicDBObject('$match', new BasicDBObject('classroom', params.classroom))
        queryPipe << matchclassroom

        final DBObject unwind = new BasicDBObject('$unwind', '$students')
        final DBObject groupFields = new BasicDBObject('_id', '$students.code')
        groupFields.put("count", new BasicDBObject('$sum', 1))
        final DBObject group = new BasicDBObject('$group', groupFields)
        queryPipe << group

        List facetsList = []
        Student.collection.aggregate(queryPipe).each { fct ->

                def studentsList = fct.'_id'.student

        }

1 个答案:

答案 0 :(得分:0)

你为代码结构做了一些错误。

DBObject unwind =  new BasicDBObject('_id',new BasicDBObject('$unwind','$subjects'))

在这里,创建$ unwind Object。

DBObject group = new BasicDBObject('$group', unwind)

在这里,创建$ group对象。但是,在$ group Object内部添加$ unwind Object。