如何使用golang翻译此mongo查询cmd

db.demo.aggregate([ 
{$group:{_id:"$name",
    a:{$sum:"$a"},
    b:{$sum:"$b"}}},
{$project:{name:1,a:1,b:1,_id:1,bdiva:{$cond:[{$eq:["$a",0]},0,{$divide:["$b","$a"]}]}}},
{$sort:{bdiva:1}}
])

I'm using "gopkg.in/mgo.v2" as mongo driver for Go and I try translating this query cmd:

project := bson.M{
    "$project": bson.M{
        "name": true, "a": true, "b": true,  "_id": true,
        "bdiva": bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$a", 0}}, 0, bson.M{"$divide": []interface{}{"$b", "$a"}}}},

    },
}

group := bson.M{
    "$group": bson.M{
        "_id":  "$name",
        "a":    bson.M{"$sum": "$a"},
        "b":    bson.M{"$sum": "$b"},
    },
}

sort := bson.M{
    "$sort": bson.M{
        "bdiva": 1,
    },
}

but I can't get bdiva right, how should I fix it? ------what I tried---- I execute the cmd in shell and get the result: bdiva is therefield bdiva is outputted, but when I run the go code,it Only output: bdiva not found

field bdiva is missing,why?

The complete code:

func AggregateQueryDemo() {
    println("//<<-------------------------AggregateQueryDemo start-----------")
    start := time.Now()

    session, err := mgo.Dial(ADDRESSPORT)
    if err != nil {
        return
    }
    defer session.Close()
    c := session.DB(DB).C(COLLECTION)

    project := bson.M{
        "$project": bson.M{
            "name": true, "a": true, "b": true, "suma": true, "sumb": true, "_id": true,
            "bdiva": bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$suma", 0}}, 0, bson.M{"$divide": []interface{}{"$sumb", "$suma"}}}},
        },
    }

    group := bson.M{
        "$group": bson.M{
            "_id":  "$name",
            "sumb": bson.M{"$sum": "$b"},
            "suma": bson.M{"$sum": "$a"},
        },
    }

    sort := bson.M{
        "$sort": bson.M{
            "bdiva": 1,
        },
    }

    operations := []bson.M{project, group, sort}
    pipe := c.Pipe(operations)

    ret := []interface {
    }{}
    err = pipe.All(&ret)
    if err != nil {
        panic(err.Error())
        return
    }
    for k, v := range ret {
        fmt.Printf("%+v: %+v
", k, v)
    }
    fmt.Printf(" %v microseconds
", time.Since(start)/1000000)
    println("//---------------------------AggregateQueryDemo end----------->>")
}

Query conditions are right written,and these are worth being noticed :

  1. to writh $eq condition you should use interface slice in go
  2. Operation Order is important, to fix issue of the problem ,it should be

    operations := []bson.M{group, project, sort}

thank Blake Seven