Strongly typed queries with the Go driver

Hi, I’m new with the mongodb driver for mongo but I’m quite experienced with other languages drivers.
I’m using the struct tags to insert document and I was wondering if there’s a way to use them (or any other way) to write strongly typed queries, projections, sorting documents.

I tried to look around but it seems everyone uses just strings over and over, and I hoped there would be a better way. I investigated a bit the bson package with the idea of marshalling the document myself but I cannot cover all cases.

Are there proper ways to do this?

Thank you

I think the design pattern is to cover this on the MongoDB side with schema validation rules.

Thank you for your answer Jack, but I’m not sure this would solve my problem. I’m looking for a method to write strongly typed code, possibly reusing the struct I already wrote, instead of using strings.

Thank you and sorry if the question was not clear.

You know your own code best, but out of curiosity, what’s the problem looking for this solution?

  • Any code that doesn’t touch MongoDB can be as strongly typed as Go supports.
  • Any code that touches MongoDB is tightly constrained by the intersection of any validation rules and the Bson types you use.

This is not enough? Again, no argument, just trying to understand what you’re seeing that I’m missing.

I’m looking for a way to do something similar to what Builders in the dotnet driver enable users to do, strongly typed queries.

Instead of writing

coll.FindOne(context.TODO(), bson.D{{"title", "The Room"}})

where “title” is a string, I would like to write something like this (from the dotnet driver)

var builder = Builders<Widget>.Filter;
var filter = builder.Eq(widget => widget.X, 10) & builder.Lt(widget => widget.Y, 20);

And not only for queries, which for most of them I can marshal the document from a struct, but also for projections and sorting.

Let me know if it’s still not clear.

Okay, I think I understand now.

In answer to your question, it seems to me that Golang considers the “Builder” pattern exhibited by the C#/.NET driver to be a liability more than an asset. Vide the Go Proverbs:

This is not to say that one cannot implement such a framework in Go, but it would be left to the programmer to do so.