泛舟湖上清波郎朗
这是在MongoDB数据库中存储结构类型数据的示例代码要从 mongodb 获取 JSON 格式的数据,您可以使用 json.Marshal() 方法package mainimport ( "context" "fmt" "log" "io/ioutil" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options")type Person struct { ID int `json:"_id"` Age int `json:"Age"` City string `json:"city"`}func main() { clientOptions := options.Client().ApplyURI("mongodb://127.0.0.1:27017") client, err := mongo.Connect(context.TODO(), clientOptions) if err != nil { log.Fatal(err) } ctx, _ := context.WithTimeout(context.Background(), 3*time.Second) fmt.Println("Connected to MongoDB!") collection := client.Database("db_name").Collection("collection_name") byteValues, err := ioutil.ReadFile("docs.json") if err != nil { fmt.Println("ioutil.ReadFile ERROR:", err) } else { fmt.Println("ioutil.ReadFile byteValues TYPE:", reflect.TypeOf(byteValues)) fmt.Println("byteValues:", byteValues, "n") fmt.Println("byteValues:", string(byteValues)) } for i := range docs { doc := docs[i] fmt.Println("ndoc _id:", doc.ID) fmt.Println("doc Field Str:", doc.ID) result, insertErr := col.InsertOne(ctx, doc) if insertErr != nil { fmt.Println("InsertOne ERROR:", insertErr) } else { fmt.Println("InsertOne() API result:", result) }}