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

时间:2016-03-15 03:18:13

标签: mongodb go

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,
    },
}

我正在使用“gopkg.in/mgo.v2”作为Go的mongo驱动程序 我尝试翻译此查询cmd:

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\n", k, v)
    }
    fmt.Printf(" %v microseconds\n", time.Since(start)/1000000)
    println("//---------------------------AggregateQueryDemo end----------->>")
}

但我无法正确 bdiva ,我该如何解决? ------我试过的---- 我在shell中执行cmd并获得结果: bdiva is there 字段 bdiva 输出, 但是当我运行go代码时,它只输出: bdiva not found

字段 bdiva 缺少,为什么?

完整的代码:

user

1 个答案:

答案 0 :(得分:0)

查询条件是正确的,这些值得注意:

  1. to writh $ eq condition你应该在go
  2. 中使用interface slice
  3. 操作顺序很重要,要解决问题的问题,应该是

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

  4. 感谢Blake Seven