一、golang 使用 mongoDB
在Go语言中使用MongoDB需要使用第三方的MongoDB驱动程序库,例如官方的MongoDB Go Driver、mgo和gomongo等。以下是使用官方MongoDB Go Driver连接MongoDB数据库的基本步骤:
-
安装MongoDB Go Driver:
go get go.mongodb.org/mongo-driver/mongo
-
建立MongoDB连接:
import ( "context" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") client, err := mongo.Connect(context.Background(), clientOptions) if err != nil { log.Fatal(err) } err = client.Ping(context.Background(), nil) if err != nil { log.Fatal(err) } defer client.Disconnect(context.Background()) fmt.Println("Connected to MongoDB!") }
-
创建一个MongoDB数据库、集合和文档:
collection := client.Database("mydb").Collection("users") user := bson.M{"name": "John", "age": 35} res, err := collection.InsertOne(context.Background(), user) if err != nil { log.Fatal(err) } fmt.Println("Inserted document with ID:", res.InsertedID)
-
查询和过滤MongoDB文档:
filter := bson.M{"name": "John"} var result bson.M err = collection.FindOne(context.Background(), filter).Decode(&result) if err != nil { log.Fatal(err) } fmt.Println("Found document:", result)
总之,在Go语言中使用MongoDB可以通过第三方MongoDB驱动程序库来实现,这使得能够轻松连接到MongoDB数据库,执行CRUD操作,以及使用MongoDB的强大功能。