I want to test the Golang MongoDB driver from MongoDB (https://github.com/mongodb/mongo-go-driver, currently in alpha state).
The example in the package documentation (https://godoc.org/github.com/mongodb/mongo-go-driver/mongo) isn't very help for me. What I'm looking for are simple (but complete) examples for the basic CRUD operations.
Since the MongoDB Go driver is currently alpha, the documentation is still being worked on. However, you can find examples destined for documentation in the driver's GitHub repo: examples/documentation_examples/examples.go. There is also a test harness in the same directory (examples-test.go
) to ensure all the code examples work as expected.
If you search examples.go
for // Start Example
you will find snippets of code demarcated with a matching // End Example
. The numbering of examples is somewhat opaque, but those are actually standard references used to extract driver code snippets for the MongoDB manual.
In particular, the initial code examples should match up with the tabbed code blocks within the MongoDB CRUD Operations section of the manual.
Using func InsertExamples()
in examples.go
to illustrate:
Examples in this function are used by the Insert Documents tutorial.
Example 2 is the find()
query to retrieve the document that was just inserted.
In most cases the order of code examples should follow the order of the code blocks in the documentation.
@Stennie: Thanks for the detailed explanations. I had seen the mentioned examples already, but they are looking very low level and not Go idiomatic for me. So I came up to this:
// Size defines the item size
type Size struct {
H int
W float64
Uom string
}
// Item defines an item
type Item struct {
OID objectid.ObjectID `bson:"_id,omitempty"` // omitempty not working
Item string
Qty int
Tags []string
Size Size
}
func main() {
// connect to MongoDB
client, err := mongo.Connect(context.Background(), "mongodb://localhost:27017", nil)
if err != nil {
log.Fatal(err)
}
db := client.Database("mongosample")
inventory := db.Collection("inventory")
// write document
itemWrite := Item{Item: "canvas", Qty: 100, Tags: []string{"cotton"}, Size: Size{H: 28, W: 35.5, Uom: "cm"}}
itemWrite.OID = objectid.New()
fmt.Printf("itemWrite = %v
", itemWrite)
result, err := inventory.InsertOne(context.Background(), itemWrite)
if err != nil {
log.Fatal(err)
}
fmt.Printf("result = %#v
", result)
// read documents
cursor, err := inventory.Find(
context.Background(),
bson.NewDocument(bson.EC.String("item", "canvas")),
)
if err != nil {
log.Fatal(err)
}
defer cursor.Close(context.Background())
itemRead := Item{}
for cursor.Next(context.Background()) {
err := cursor.Decode(&itemRead)
if err != nil {
log.Fatal(err)
}
fmt.Printf("itemRead = %v
", itemRead)
}
}
I have no need to control the ObjectID in the application and want to let the driver or database generate the ID on demand. Problem here: I couldn't find a way to omit the ID. This bson:"_id,omitempty"
isn't working. It leeds to an OID with everything set to zero 'ObjectID("000000000000000000000000")'. Maybe a general problem because ObjectID is an array and not a slice: type ObjectID [12]byte
I wrote code like this in my recent project and it worked well. Request you to kindly try it out.
FYI : I am using official Go - Mongo DB driver
.
import "go.mongodb.org/mongo-driver/bson/primitive"
and
type Item struct {
OID primitive.ObjectID `json:"id,omitempty" bson:"_id,omitempty"`
Item string
Qty int
Tags []string
Size Size
}