在golang / mongodb聚合查询中复合文字中缺少类型

时间:2016-04-12 18:15:57

标签: go aggregate

我想在golang中编写mongo查询。我的mongo查询是 -

aggregate([
    {$match: {$and :
        [
            {"stream" : "CS"},
            {"semester" : "sem3"},
            {"section" : "A"}
        ]

    }},
    {$unwind:  '$atndnc'},
    { $group: { _id:{rollno: "$atndnc.rollno",attend:"$atndnc.attend"},count: { $sum: 1 }}},
    {  $project:
    {  _id: '$_id.rollno',
        'attend' : '$_id.attend',
        'count' : '$count'
    }}
])

我的Go代码是 -

cond:=[]bson.M{
    bson.M{"$match": bson.M{"$and ":[]interface{}{
        bson.M{"stream" : srchobj.Stream},
        bson.M{"semester" : srchobj.Semester},
        bson.M{"section" : srchobj.Section},
        bson.M{"college_id":srchobj.College_id},
        bson.M{"date":bson.M{"$gt":srchobj.Startdate,"$lt":srchobj.Enddate}}}}},
    bson.M{"$unwind":  "$atndnc"},
    bson.M{"$group":bson.M{"_id":{"rollno":bson.M{"$atndnc.rollno"},"attend":bson.M{"$atndnc.attend"}},"count":bson.M{"$sum":1}}},
    bson.M{"$project":bson.M{"_id":"$_id.rollno","count":"$_id.count"}}}

但是它给出了错误"复合文字中缺少的类型"在

    bson.M{"$group":bson.M{"_id":{"rollno":bson.M{"$atndnc.rollno"},"attend":bson.M{"$atndnc.attend"}},"count":bson.M{"$sum":1}}},

在这一行。我现在该怎么办?

2 个答案:

答案 0 :(得分:2)

$ group查询中的一组大括号上缺少类型声明: {"rollno":bson.M{"$atndnc.rollno"},"attend":bson.M{"$atndnc.attend"}}

我认为应该是: bson.M{"rollno":bson.M{"$atndnc.rollno"},"attend":bson.M{"$atndnc.attend":nil}}

还有一些其他初始化的东西,比如只用字符串键初始化(记住,bson.M只是map [string] interface {}的别名

答案 1 :(得分:0)

感谢您的支持。通过这样做,我获得了理想的输出。

cond :=[]bson.M{
    bson.M{"$match": bson.M{
            "stream" : srchobj.Stream,
            "semester" : srchobj.Semester,
            "section" : srchobj.Section,
            "college_id":srchobj.College_id,
            "date":bson.M{
                "$gt":srchobj.Startdate,
                "$lt":srchobj.Enddate},
     },
    },
    bson.M{"$unwind":  "$atndnc"},
    bson.M{"$group":bson.M{
        "_id":bson.M{
            "rollno":"$atndnc.rollno",
            "attend":"$atndnc.attend",
            "name":"$atndnc.name",
            },
        "count":bson.M{"$sum":1},
        },
    },
    bson.M{"$project":bson.M{
        "rollno":"$_id.rollno",
        "name":"$_id.name",
        "count":"$count",
        "attend":"$_id.attend",
        },
    },
    bson.M{"$sort":bson.M{"rollno":1}},
}