在Go语言中,使用官方提供的MongoDB驱动程序进行CRUD操作十分方便。下面介绍一些基本的CRUD操作方法。
- 连接MongoDB
连接到MongoDB可以通过调用mongo.Connect()函数来实现,如下所示:
client, err := mongo.Connect(context.Background(), options.Client().ApplyURI(“mongodb://localhost:27017”))
- 插入文档
插入一个新文档可以通过调用Collection对象的InsertOne()或InsertMany()方法来实现。例如,插入一个名为“John”的用户信息:
user := bson.M{“name”: “John”, “age”: 30} collection := client.Database(“testdb”).Collection(“users”) res, err := collection.InsertOne(context.Background(), user) if err != nil {
log.Fatal(err)
} fmt.Println(res.InsertedID)
- 查询文档
查询文档可以通过调用Collection对象的Find()或FindOne()方法来实现。例如,查询所有名字为“John”的用户信息:
filter := bson.M{“name”: “John”} var results []bson.M cur, err := collection.Find(context.Background(), filter) if err != nil {
log.Fatal(err)
} defer cur.Close(context.Background()) for cur.Next(context.Background()) {
var result bson.M
err := cur.Decode(&result)
if err != nil {
log.Fatal(err)
}
results = append(results, result)
} if len(results) > 0 {
fmt.Println(results)
} else {
fmt.Println("No matching documents found")
}
- 更新文档
更新文档可以通过调用Collection对象的UpdateOne()或UpdateMany()方法来实现。例如,将名字为“John”的用户的年龄更新为35:
filter := bson.M{“name”: “John”} update := bson.M{“$set”: bson.M{“age”: 35}} res, err := collection.UpdateOne(context.Background(), filter, update) if err != nil {
log.Fatal(err)
} fmt.Printf(“Matched %v documents and updated %v documents.\n”, res.MatchedCount, res.ModifiedCount)
- 删除文档
删除文档可以通过调用Collection对象的DeleteOne()或DeleteMany()方法来实现。例如,删除所有名字为“John”的用户信息:
filter := bson.M{“name”: “John”} res, err := collection.DeleteMany(context.Background(), filter) if err != nil {
log.Fatal(err)
} fmt.Printf(“Deleted %v documents.\n”, res.DeletedCount)