1
votes

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.

3
Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.Neil Lunn
If you actually look yourself though, that's not the "only" option for connecting to MongoDB with Go. 3rd party offerings have been around for years, and they are not in "alpha", so their API is more stable. I'm sure once "out of Alpha" MongoDB will be happy to expand on their own manual or even "unit tests", which is usually where I learn about different language implementations. Unit tests usually show you a lot.Neil Lunn

3 Answers

5
votes

@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\n", itemWrite)

    result, err := inventory.InsertOne(context.Background(), itemWrite)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("result = %#v\n", 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\n", 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

1
votes

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:

In most cases the order of code examples should follow the order of the code blocks in the documentation.

0
votes

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
}