解组 bson.D 对象 (Golang)

Unmarshalling a bson.D object (Golang)

我会尽量说清楚。我正在使用 MongoDB 和 Model-Vew-Controller 架构构建一个简单的审计日志记录 API。作为功​​能的一部分,用户可以使用 http 端点请求数据。当命中端点时,控制器包调用模型包,并执行以下代码:

// The GetResourceData function takes the resource, and provides the log data for that resource, sorted by // date and time. It also takes a context.context, and a *mongo.Client as parameters.

func GetResourceData(ctx context.Context, CL *mongo.Client, Resource string) error { ourDatabase := CL.Database("Event_Database") eventsCollection := ourDatabase.Collection("Events")

opts := options.Find()
opts.SetSort(bson.D{{"Date", -1}, {"Time", -1}})

filterCursor, err := eventsCollection.Find(
    ctx,
    bson.M{"Resource": Resource},
    opts)

if err != nil {

    log.Fatal(err)
}

defer filterCursor.Close(ctx)
for filterCursor.Next(ctx) {

    var eventsFiltered []bson.D
    if err = filterCursor.All(ctx, &eventsFiltered); err != nil {
        log.Fatal(err)
    }

    fmt.Println(eventsFiltered)

}

return err
}

效果很好,如您所见,我已将 eventsFiltered 打印到终端。然而,它在那里并没有多大用处,我需要将它打印到屏幕上。我有一个函数可以在带有 http.ResponseWriter 的视图包中执行此操作,但是 - 我无法弄清楚如何将 bson.D 转换为字符串格式,因此我可以将其作为参数干净地传递.如果我尝试 bson.Unmarshall;

            var cookie []byte
    bson.Unmarshal(cookie, eventsFiltered)
    s := string(cookie)
    fmt.Println("Events filtered as a string is: ", s)
    fmt.Println("Events filtered as a byte slice is: ", cookie)

我得到以下信息;

过滤为字符串的用户是:

作为字节片过滤的用户是:[]

...空字符串或空字节片。我知道我缺少一些非常简单的东西,但我看不到它!

如有任何帮助,我们将不胜感激。有问题请追问

谢谢, A

首先,如果您使用 filterCursor.All(ctx, &eventsFiltered),则不需要遍历所有集合或关闭游标(游标方法 All(...) 会为您完成)。


关于你的问题,你可以这样操作:

        var eventsFiltered []bson.D
        if err = filterCursor.All(ctx, &eventsFiltered); err != nil {
            log.Fatal(err)
        }
        for _, event := range eventsFiltered {
            for _, keyValPair := range event {
                fmt.Printf("key is %s; val is %v", keyValPair.Key, keyValPair.Value)
            }
        }

或者,如果元素的顺序无关紧要,请考虑解组为 bson.M:

        var eventsFiltered []bson.M
        if err = filterCursor.All(ctx, &eventsFiltered); err != nil {
            log.Fatal(err)
        }
        for _, event := range eventsFiltered {
            for key, val := range event {
                fmt.Printf("key is %s; val is %v", key, val)
            }
        }

所以,整个解决方案是:

func GetResourceData(ctx context.Context, CL *mongo.Client, Resource string) error {
    ourDatabase := CL.Database("Event_Database")
    eventsCollection := ourDatabase.Collection("Events")

    opts := options.Find()
    opts.SetSort(bson.D{{"Date", -1}, {"Time", -1}})

    filterCursor, err := eventsCollection.Find(
        ctx,
        bson.M{"Resource": Resource},
        opts)

    if err != nil {
        log.Fatal(err)
    }

    if filterCursor.Next(ctx) {
        var eventsFiltered []bson.M
        if err = filterCursor.All(ctx, &eventsFiltered); err != nil {
            log.Fatal(err)
        }
        // If you need ordered print, uncomment the following lines and comment out following uncommented for loop
        //        for _, event := range eventsFiltered {
        //            for _, keyValPair := range event{
        //                fmt.Printf("key is %s; val is %v", keyValPair.Key, keyValPair.Value)
        //            }
        //        }
        for _, event := range eventsFiltered {
            for key, val := range event {
                fmt.Printf("key is %s; val is %v", key, val)
            }
        }

    }
    return nil
}