下面是使用Go在MongoDB中进行CRUD操作的完整攻略:
go get go.mongodb.org/mongo-driver/mongo
在Go中连接MongoDB需要使用mongo.Connect方法,如下所示:
client, err := mongo.Connect(context.Background(), options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
log.Fatal(err)
}
在MongoDB中插入数据需要向MongoDB服务器发送一个JSON格式的文档.在Go中,我们需要将文档封装成一个bson.M类型(这种类型表示一个map[string]interface{}类型),然后使用collection.InsertOne方法插入数据,如下所示:
collection := client.Database("test").Collection("students")
student := bson.M{"name": "Tom", "age": 18}
result, err := collection.InsertOne(context.Background(), student)
if err != nil {
log.Fatal(err)
}
id := result.InsertedID
fmt.Println("Inserted document with ID:", id)
其中client.Database("test").Collection("students")表示我们需要在MongoDB中名为test的数据库,students集合中插入数据.
cursor, err := collection.Find(context.Background(), bson.M{"age": bson.M{"$gte": 18}})
if err != nil {
log.Fatal(err)
}
filter := bson.M{"name": "Tom"}
update := bson.M{"$set": bson.M{"age": 20}}
result, err := collection.UpdateOne(context.Background(), filter, update)
if err != nil {
log.Fatal(err)
}
fmt.Println("Matched documents:", result.MatchedCount)
fmt.Println("Modified documents:", result.ModifiedCount)
在MongoDB中删除数据需要使用DeleteOne或DeleteMany方法,这两个方法会根据过滤条件删除匹配的文档.下面的示例将删除名字为Tom的学生:
filter := bson.M{"name": "Tom"}
result, err := collection.DeleteOne(context.Background(), filter)
if err != nil {
log.Fatal(err)
}
fmt.Println("Deleted documents:", result.DeletedCount)
在这个示例中,filter := bson.M{"name": "Tom"}表示需要删除名字为Tom的学生.
到此,我们已经完成了使用Go在MongoDB中进行CRUD操作的演示.以上的操作都是常见的MongoDB操作,在实际应用中也经常使用到.