How to reliable access collection name when using event.CommandMonitor in Golang


In our application, we are relying on the *event.CommandMonitor option when creating clients to log structured information about the command we are running, and one of the fields we would be interesting in accessing is the collection name. However the received *event.CommandStartedEvent struct doesn’t directly have this information (even though it contains the bson.Raw command where you could potentially access it).

So my question is if there’s a reliable way to access the collection name within the scope of this function, or if it’s safe to assume bsonCommand[evt.CommandName] will always contain the collection name?

Thanks in advance!

Hey @Rodrigo_Arguello welcome and thanks for the question!

As far as I can tell, the collection name is always the value associated with the command name (i.e. bsonCommand[evt.CommandName]). Check out the Database Commands section of the MongoDB Manual for a more comprehensive answer.

As far as the actual CommandStartedEvent (and other command events), the information provided is specified in the Events API section of the MongoDB driver specifications. That specification doesn’t currently include collection name, but I can definitely see a use case for it.

I’ve proposed a change to the drivers specification to add database name and collection name to all command logging and monitoring events (see DRIVERS-2575).

@Rodrigo_Arguello can you tell me more about your use case and why you need access to the collection name so I can include that in the ticket?

Hi @Matt_Dale and thanks for your reply and your proposal!

As for the use case, I work in Datadog’s APM product where we support tracing some libraries out of the box for different languages.

We support the official mongodb drivers for some languages and we wanted to start adding more information to the spans we generate (in this case the collection when applies for the command the user is running).

Also I recently noticed this limitation is also present in other official MongoDB drivers like the Ruby one (not sure about the rest), so it would be awesome if this change would be implemented across all of them.

I hope this is helpful for your proposal. Also looking forward for it to be implemented!