前端之家收集整理的这篇文章主要介绍了
golang monogdb,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package main import ( "fmt" "labix.org/v2/mgo" "labix.org/v2/mgo/bson" ) type Depta struct { Id string `bson:"_id"` Count int Ename string Sal int Mgrsal int Subsal int Davgsal int Dsumsal int Dcount int } func main() { session,err := mgo.Dial("127.0.0.1") if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic,true) c := session.DB("lizd").C("dept") fmt.Println("-----第一小题答案:------") /* 第一小题:db.dept.aggregate( [ {$unwind: "$emp" },{$group: { _id: "$dname",count: { "$sum": 1 } } } ] ) */ pipe := c.Pipe([]bson.M{{"$unwind": "$emp"},{"$group": bson.M{"_id": "$dname","count": bson.M{"$sum": 1}}}}) result := Depta{} iter := pipe.Iter() var i int fmt.Printf("%2s%16s%8s\n","序号","部门
名称","雇员
数量") for iter.Next(&result) { i = i + 1 fmt.Printf("%4d%20s%10d\n",i,result.Id,result.Count) } /*第二小题: db.dept.aggregate( { $unwind : "$emp" },{ $project : { _id : 0,ename : "$emp.ename",sal : "$emp.sal" }},{ $sort : { "sal" : -1 } },{ $limit : 3 } ); */ fmt.Println("\n\n-----第二小题答案:------") pipe = c.Pipe([]bson.M{{"$unwind": "$emp"},{"$project": bson.M{"_id": 0,"ename": "$emp.ename","sal": "$emp.sal"}},{"$sort": bson.M{"sal": -1}},{"$limit": 3}}) iter = pipe.Iter() i = 0 fmt.Printf("%2s%16s%8s\n","雇员姓名","薪水") for iter.Next(&result) { i = i + 1 fmt.Printf("%4d%20s%10d\n",result.Ename,result.Sal) } /*第三小题: db.dept.aggregate( {$unwind : "$emp" },{ $project : { ename : "$emp.ename",sal : "$emp.sal",mgrsal : "$emp.mgr.sal",subsal : {$subtract : ["$emp.sal","$emp.mgr.sal"]},_id : 0 }},{$match : {"subsal" : {$gt : 0} } } ); */ fmt.Println("\n\n-----第三小题答案:------") pipe = c.Pipe([]bson.M{{"$unwind": "$emp"},"sal": "$emp.sal","mgrsal": "$emp.mgr.sal","subsal": bson.M{"$subtract": [2]string{"$emp.sal","$emp.mgr.sal"}}}},{"$match": bson.M{"subsal": bson.M{"$gt": 0}}}}) iter = pipe.Iter() i = 0 fmt.Printf("%2s%16s%8s%8s\n","薪水","上级薪水") for iter.Next(&result) { i = i + 1 fmt.Printf("%4d%20s%10d%10d\n",result.Sal,result.Mgrsal) } /*第四小题: db.dept.aggregate( {$unwind : "$emp" },{$group : {_id : "$dname",average
score: {$avg:"$emp.sal"},totalPop : { $sum : "$emp.sal" },countPop : { $sum : 1 } } } ) 注解:因为 aggregate 不能完成后续求平均后再比较的操作,所以程序处理求公司平均数 与 比较大小 */ fmt.Println("\n\n-----第四小题答案:------") pipe = c.Pipe([]bson.M{{"$unwind": "$emp"},"davgsal": bson.M{"$avg": "$emp.sal"},"dsumsal": bson.M{"$sum": "$emp.sal"},"dcount": bson.M{"$sum": 1}}}}) iter = pipe.Iter() mySlice := make([]Depta,10) var dsum int var dcount int for iter.Next(&result) { dsum = dsum + result.Dsumsal dcount = dcount + result.Dcount mySlice = append(mySlice,result) } davg := dsum / dcount fmt.Printf("%2s%16s%8s%8s\n","部门平均","公司平均") for i,v := range mySlice { if v.Davgsal > davg { fmt.Printf("%4d%20s%10d%10d\n",v.Id,v.Davgsal,davg) } } }
原文链接:https://www.f2er.com/go/191322.html