How can I view raw input/output from my queries?

I’m attempting to write something that enables me to see the raw response that is returned from mongo. Essentially, we run pipeline aggregations with many different data types - none of them a specific kind. Sometimes, it’s difficult to tell why the result isn’t unpacking cleanly into the result struct. In these cases, I’m attempting to create a debug mode that will print out the raw response from mongo (in the same format that you see on the mongo CLI essentially when you run a query - or something close).
Then you would be able to see what mongo is returning and adjust your query or data type accordingly.

I’ve run into a couple problems though - Ultimately, what should I be using to do this? Is there some kind of unmarshaller can I use to accomplish this perhaps? Is there a generic hook for all data types or perhaps I could call the default marshaller function at the end of this function?

Any guidance would be appreciated.

Hi @TopherGopher,

The easiest way to do this would be via our Command Monitoring API. If you’re just looking to log commands and server responses, you could do something like this:

monitor := &event.CommandMonitor {
    Started: func(_ context.Context, e *event.CommandStartedEvent) {
        fmt.Println(e.Command)
    },
    Succeeded: func(_ context.Context, e *event.CommandSucceededEvent) {
        fmt.Println(e.Reply)
    },
    Failure: func(_ context.Context, e *event.CommandFailedEvent) {
        fmt.Println(e.Failure)
    },
}

opts := options.Client().SetMonitor(monitor)
client, err := mongo.Connect(ctx, opts)

This will log all of the commands sent to the server as well as the server’s response or an error that occurred. If you have an application that does multiple concurrent operations, the logs may have started/succeed/failed events for different operations interleaved with each other. If you want to log the CommandStartedEvent for an operation along with it’s CommandSucceededEvent/CommandFailedEvent, you can use the RequestID field in the events to correlate them (perhaps using something like Go’s sync.Map type).

– Divjot

3 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.