How to read MongoDB

I’m trying to read values from my MongoDB this is my current code

import (
	"context"
	"fmt"
	"github.com/mongodb/mongo-go-driver/mongo"
	"log"
)
// Size defines the item size
type Size struct {
	H   int
	W   float64
	Uom string
}

// Item defines an item
type Item struct {

	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("bigbackup")
	inventory := db.Collection("info_consumer_base_mongos")

	cur, err := inventory.Find(context.Background(), nil)
	if err != nil { log.Fatal(err) }
	defer cur.Close(context.Background())
	for cur.Next(context.Background()) {
		raw, err := cur.DecodeBytes()
		if err != nil { log.Fatal(err) }
		fmt.Printf("itemRead = %v\n", raw)
		// do something with elem....

	}
	if err := cur.Err(); err != nil {
		return
	}

}`

How do I select each result or loop raw so I can save the fields to a string like this?

raw[1] or raw[“FN”]

If you know total struct of raw data, you can define struct for item data and unmarshal it by json. Otherwise, you can try to unmarshal it to map[string]interface{}, and access it by data["FN"], post a simple example at: https://play.golang.org/p/kB-BPevwsaE

1 Like

OK great. I need to find a way to convert the _id to a string, this is what I have now. Its not working for me.

defer cur.Close(context.Background())
for cur.Next(context.Background()) {
	raw, err := cur.DecodeBytes()
	var ob map[string]interface{}
	_ = bson.Unmarshal(raw, &ob)
	id := bson2.ObjectId(&ob["_id"])
	fmt.Println(id.Hex())
	if err != nil { log.Fatal(err) }
	break
	// do something with elem....

}

48259060_922644911263606_1192657987978657792_n !

It’s very hard to precisely answer your question without more details like full code. e.g What’s the type of bson2?
What’s raw data? I think you can try an example to unmarshal it to get the objectid first. It’ better for me to get what the problem is if you supply example raw data and bson2 i mentioned before.

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