Golang-mongodb聚合中的Transact-SQL等价物

时间:2016-07-19 04:49:17

标签: mongodb go aggregation-framework

我有一个SQL语句,我试图使用mongodb数据库在golang中重新创建。我想重新创建的声明如下:

select date,
       sum(case when field1 = "true" then 1 else 0) trueField1,
       sum(case when field1 = "false" then 1 else 0) falseField1,
       sum(case when field2 = "true" then 1 else 0) trueField2,
       sum(case when field2 = "false" then 1 else 0) falseField2
from myTable
group by date

我需要在给定日期完成一些组合并将它们转储出去,但我不确定如何通过golang / mongodb来完成它。

已编辑:此处是我上次请求时的起点。从o1可以看出它显示了我在第一次总和/计数时要追求的东西。我还想在另一个字段中加上一个isDelivered并在同一天将它们相加,并返回同一天的计数。我可以就如何完成这项任务找到方向吗?

    o1 := bson.M{
        "$match" : bson.M {
            "retailer" : clientId,
            "isComplete" : true,
            "pkgStatus.finalized" : true,
            },
    }

    o2 := bson.M {
        "$project" : bson.M {
            "_id" : 1,
            "createdAt" : 1,
        },
    }

    o3 := bson.M{
        "$group": bson.M{
            "_id" : bson.M{ "$dayOfYear": "$createdAt" },
            "total" : bson.M{ "$sum" : 1},
            "first" : bson.M{ "$min" : "$createdAt" },
        },
    }

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

    totalMessages := []bson.M{msgsStarted, o2, o3, o4}

    operations := []bson.M{o1, o2, o3, o4}

    pipe := cMessages.Pipe(operations)

    results := []bson.M{}
    err := pipe.All(&results)

    if err != nil {
        fmt.Printf("Error: %s\n", err)
        return
    }

    for _, resultRec := range results {
        myDate := fmt.Sprintf("%s", resultRec["first"])
        fmt.Printf("%s, %d\n", myDate[0:10], resultRec["total"])
    }

EDIT2

架构定义

messages {
  "_id" : {
    "$oid" : bson.ObjectId
  },
  "isComplete" : bool,
  "status" : {
    "cancelled" : bool,
    "finalized" : bool,
    "delivered" : bool
  },
  "createdDate" : {
    "$date" : ISODate
  } 

我正在尝试使用您之前提供指导的$ cond语句并使用$和命令嵌套它,以便我可以执行以下操作:

sum(case when isComplete = true and status.finalized = true then 1 else 0)

我一直在玩以下内容:

tf1c := bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"iscomplete", true}}, 1, 0}}

但不完全不确定语法。我相信它应该遵循这样的东西,但不确定如何完全翻译它(下面是来自另一个stackoverflow线程)

"$cond": [{
    "$and": [{
      "$eq": ["isComplete", true]
    }, {
      "$eq": ["pkgStatus.finalized", true]
    }]
}, 1, 0]

再次感谢您的指导!

展开地图

你如何打开地图?

map[_id:map[date:2014-12-25 retailer:ObjectIdHex("548a9de8a4ea9d690f6df8e4")]] 

检索值。我尝试了以下但它返回null。

fmt.Printf("%s\n", resultRec["_id.date"])

1 个答案:

答案 0 :(得分:0)

确定。这样做更好,但仍然没有关于您的数据库架构的信息来了解您正在使用的数据类型。如果所有字段都是字符串格式,那么Mongo等同于SQL查询:

package main

import (
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
    "fmt"
)

func main() {
    session, err := mgo.Dial("mongodb://127.0.0.1:27017/db")

    if err != nil {
        panic(err)
    }
    defer session.Close()
    session.SetMode(mgo.Monotonic, true)

    db := session.DB("db")
    c := db.C("MyTable")

    tf1c := bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$field1", "true"}}, 1, 0}}
    ff1c := bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$field1", "false"}}, 1, 0}}
    tf2c := bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$field2", "true"}}, 1, 0}}
    ff2c := bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$field2", "false"}}, 1, 0}}

    pipe := c.Pipe(
        []bson.M{
            bson.M{
                "$group": bson.M{
                    "_id": "$date",
                    "trueField1": bson.M{"$sum": tf1c},
                    "falseField1": bson.M{"$sum": ff1c},
                    "trueField2": bson.M{"$sum": tf2c},
                    "falseField2": bson.M{"$sum": ff2c},
                },
            },
            bson.M{
                "$sort": bson.M{"_id": -1},
            },
        },
    )
    result := []bson.M{}
    err = pipe.All(&result)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%+v", result)
}

<强>更新

pipe := c.Pipe(
        []bson.M{
            bson.M{
                "$project": bson.M{
                    "year": bson.M{"$year": "$createdDate"},
                    "month": bson.M{"$month": "$createdDate"},
                    "day": bson.M{"$dayOfMonth": "$createdDate"},
                    "val": bson.M{"$cond":[]interface{}{
                        bson.M{
                            "$and": []interface{}{
                                bson.M{"$eq": []interface{}{"$isComplete", true}},
                                bson.M{"$eq": []interface{}{"$status.finalized", true}},
                            },
                        },
                        1,
                        0,
                    }},
                },
            },
            bson.M{
                "$group": bson.M{
                    "_id": bson.M{
                        "$concat": []interface{}{
                            bson.M{"$substr": []interface{}{"$year", 0, -1}},
                            "-",
                            bson.M{"$substr": []interface{}{"$month", 0, -1}},
                            "-",
                            bson.M{"$substr": []interface{}{"$day", 0, -1}},
                        },
                    },
                    "cnt": bson.M{"$sum": "$val"},
                },
            },
            bson.M{
                "$sort": bson.M{"_id": -1},
            },
        },
    )