How to persist data to MongoDB using Golang application: Create a new Golang project. Install the MongoDB driver. Connect to the MongoDB instance. Create a collection. Insert data. Query data. update data. delete data.
Golang application that persists data to MongoDB
MongoDB is a powerful non-relational database that is often used with Golang application together. This guide will show you how to persist data to MongoDB using Golang’s standard library and third-party packages.
Prerequisites
Steps
1. Create a new Golang project
go mod init myapp
2. Install the MongoDB driver
go get go.mongodb.org/mongo-driver/mongo
3. Connect to the MongoDB instance
import ( "context" "fmt" "log" "go.mongodb.org/mongo-driver/mongo" ) func main() { // 设置连接字符串 connectionString := "mongodb://localhost:27017" // 建立连接 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(connectionString)) if err != nil { log.Fatal(err) } // 延迟关闭连接 defer client.Disconnect(context.TODO()) // ... }
4. Create a collection
// 设置待创建的集合名称 collectionName := "users" // 获取集合对象 collection := client.Database("myDatabase").Collection(collectionName)
5. Insert data
// 创建一个文档 user := map[string]interface{}{ "name": "John Doe", "age": 30, } // 将文档插入集合中 insertResult, err := collection.InsertOne(context.TODO(), user) if err != nil { log.Fatal(err) } // 打印插入后的 ID fmt.Printf("Inserted document with ID: %v\n", insertResult.InsertedID)
6. Query data
// 设置要查询的过滤器 filter := bson.D{{"name", "John Doe"}} // 查询集合 cursor, err := collection.Find(context.TODO(), filter) if err != nil { log.Fatal(err) } // 迭代查询结果 for cursor.Next(context.TODO()) { var result map[string]interface{} err := cursor.Decode(&result) if err != nil { log.Fatal(err) } fmt.Printf("%v\n", result["name"]) } // 关闭游标 cursor.Close(context.TODO())
7. Update data
// 设置要更新的过滤条件 filter := bson.D{{"name", "John Doe"}} // 设置要更新的字段和值 update := bson.D{{"$set", bson.D{{"age", 31}}}} // 更新文档 updateResult, err := collection.UpdateOne(context.TODO(), filter, update) if err != nil { log.Fatal(err) } // 打印修改的文档数目 fmt.Printf("%v document(s) updated\n", updateResult.ModifiedCount)
8. Delete data
// 设置要删除的过滤条件 filter := bson.D{{"name", "John Doe"}} // 删除文档 deleteResult, err := collection.DeleteOne(context.TODO(), filter) if err != nil { log.Fatal(err) } // 打印删除的文档数目 fmt.Printf("%v document(s) deleted\n", deleteResult.DeletedCount)
The above is the detailed content of How to integrate with golang framework?. For more information, please follow other related articles on the PHP Chinese website!