ZBLOG

golang mongodb crud操作

在Go语言中,使用官方提供的MongoDB驱动程序进行CRUD操作十分方便。下面介绍一些基本的CRUD操作方法。

  1. 连接MongoDB

连接到MongoDB可以通过调用mongo.Connect()函数来实现,如下所示:

client, err := mongo.Connect(context.Background(), options.Client().ApplyURI(“mongodb://localhost:27017”))

  1. 插入文档

插入一个新文档可以通过调用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)

  1. 查询文档

查询文档可以通过调用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")

}

  1. 更新文档

更新文档可以通过调用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)

  1. 删除文档

删除文档可以通过调用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)

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=6734

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?