介绍
如何在mongodb中使用golang驱动?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
<强>使用教程如下:强>
导入
go get github.com/mongodb/mongo-go-driver/mongo
链接mongo服务
if 客户,,err =, mongo.Connect (getContext ()), url);, err !=, nil { checkErr才能(err) 以前,}>判断服务是否可用
if err =, client.Ping (getContext ()), readpref.Primary ());, err !=, nil { checkErr才能(err) 以前,}>选择数据库和集合
collection =, client.Database (“testing_base") .Collection (“howie")删除这个集合
collection.Drop (getContext ())插入一条数据
if insertOneRes,, err =, collection.InsertOne (getContext ()), howieArray [0]);, err !=, nil { checkErr才能(err) ,} ,fmt.Printf (“InsertOne插入的消息ID: % v \ n",, insertOneRes.InsertedID)批量插入数据
if insertManyRes,, err =, collection.InsertMany (getContext ()), howieArray);, err !=, nil { checkErr才能(err) ,} ,fmt.Printf (“InsertMany插入的消息ID: % v \ n",, insertManyRes.InsertedIDs)查询单条数据
if err =, collection.FindOne (getContext ()), bson.D {{“name",,“howie_2"},, {“age", 11}}) .Decode(及豪伊);,err !=, nil { checkErr才能(err) ,} ,fmt.Printf (“FindOne查询到的数据:% v \ n",,豪伊)查询单条数据后删除该数据
if err =, collection.FindOneAndDelete (getContext ()), bson.D {{“name",,“howie_3"}}) .Decode(及豪伊);,err !=, nil { checkErr才能(err) ,} ,fmt.Printf (“FindOneAndDelete查询到的数据:% v \ n",,豪伊)询单条数据后修改该数据
if err =, collection.FindOneAndUpdate (getContext ()), bson.D {{“name",,“howie_4"}},, bson.M {“set"美元:bson.M {“name":,“这条数据我需要修改了“}}).Decode(及豪伊);,err !=, nil { checkErr才能(err) ,} ,fmt.Printf (“FindOneAndUpdate查询到的数据:% v \ n",,豪伊)查询单条数据后替换该数据(以前的数据全部清空)
if err =, collection.FindOneAndReplace (getContext ()), bson.D {{“name",,“howie_5"}},, bson.M {“hero":,“这条数据我替换了“}).Decode(及豪伊);,err !=, nil { checkErr才能(err) ,} ,fmt.Printf (“FindOneAndReplace查询到的数据:% v \ n",,豪伊)一次查询多条数据(查询createtime>=3,限制取2条,createtime从大到小排序的数据)
if 游标,,err =, collection.Find (getContext ()), bson.M {“createtime": bson.M {“gte"美元:2}},,options.Find () .SetLimit (2), options.Find () .SetSort (bson.M {“createtime": 1}));, err !=, nil { checkErr才能(err) ,} ,if err =, cursor.Err ();, err !=, nil { checkErr才能(err) ,} ,defer cursor.Close (context.Background ()) ,for cursor.Next (context.Background ()), { if 才能;err =, cursor.Decode(及豪伊);,err !=, nil { ,,checkErr (err) ,,} howieArrayEmpty 才能=,附加(howieArrayEmpty,豪伊) ,} ,fmt.Printf(“发现查询到的数据:% v \ n",, howieArrayEmpty)查询集合里面有多少数据
if 大小,err =, collection.Count (getContext (),, nil);, err !=, nil { checkErr才能(err) ,} ,fmt.Printf(“数里面有多少条数据:% d \ n",,大小)查询集合里面有多少数据(查询createtime>=3的数据)
if 大小,err =, collection.Count (getContext ()), bson.M {“createtime": bson.M {“gte"美元:,3}});,err !=, nil { checkErr才能(err) ,} ,fmt.Printf(“数里面有多少条数据:% d \ n",,大小)修改一条数据
if 更新器,,err =, collection.UpdateOne (getContext ()), bson.M {“name":“howie_2"},, bson.M {“set"美元:bson.M {“name":,“我要改了他的名字“}});,err !=, nil { checkErr才能(err) ,} null null null null null null null null null null如何在mongodb中使用golang驱动