Install the MongoDB Go Driver

The MongoDB Go Driver is made up of several packages. If you are just using go get, you can install the driver using:

  1. go get github.com/mongodb/mongo-go-driver
  2. // go get github.com/mongodb/mongo-go-driver/mongo

Example code

  1. package main
  2. import (
  3. "context"
  4. //"encoding/json"
  5. "fmt"
  6. "github.com/mongodb/mongo-go-driver/bson"
  7. "github.com/mongodb/mongo-go-driver/mongo"
  8. "github.com/mongodb/mongo-go-driver/mongo/options"
  9. "log"
  10. "time"
  11. )
  12. func main() {
  13. // 连接数据库
  14. ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) // ctx
  15. opts := options.Client().ApplyURI("mongodb://localhost:27017") // opts
  16. client, _ := mongo.Connect(ctx,opts) // client
  17. // 使用
  18. db := client.Database("mark") // database
  19. stu := db.Collection("student") // collection
  20. // 插入数据 直接使用student struct实例
  21. xm := Student{Name:"小明",Age:17,Sex:M,}
  22. res, _ := stu.InsertOne(ctx,xm)
  23. // 查询数据 bson.D{}创建查询条件
  24. cur, err := stu.Find(ctx, bson.D{}) // find
  25. CheckError(err)
  26. // 延时关闭游标
  27. defer cur.Close(ctx)
  28. for cur.Next(ctx) {
  29. // 可以decode到bson.M 也就是一个map[string]interface{}中
  30. // 也可以直接decode到一个对象中
  31. s := &Student{}
  32. var result bson.M
  33. err := cur.Decode(&result) // decode 到map
  34. err = cur.Decode(s) // decode 到对象
  35. CheckError(err)
  36. // do something with result....
  37. // 可以将map 或对象序列化为json
  38. //js ,_:=json.Marshal(result)
  39. //json.Unmarshal(js,s) //反学序列化回来
  40. fmt.Println(s)
  41. }
  42. }
  43. type Gender uint8
  44. const (
  45. M = iota
  46. F
  47. )
  48. type Student struct {
  49. Name string `json:"name"`
  50. Age int `json:"age"`
  51. Sex Gender `json:"gender"`
  52. }
  53. func CheckError( err error){
  54. if err != nil {
  55. log.Println(err.Error())
  56. return
  57. }
  58. }

Use BSON Objects in Go

JSON documents in MongoDB are stored in a binary representation called BSON (Binary-encoded JSON). Unlike other databases that store JSON data as simple strings and numbers, the BSON encoding extends the JSON representation to include additional types such as int, long, date, floating point, and decimal128. This makes it much easier for applications to reliably process, sort, and compare data. The Go Driver has two families of types for representing BSON data: The D types and the Raw types.

The D family of types is used to concisely build BSON objects using native Go types. This can be particularly useful for constructing commands passed to MongoDB. The D family consists of four types:

  • D: A BSON document. This type should be used in situations where order matters, such as MongoDB commands.
  • M: An unordered map. It is the same as D, except it does not preserve order.
  • A: A BSON array.
  • E: A single element inside a D.

Here is an example of a filter document built using D types which may be used to find documents where the name field matches either Alice or Bob:

  1. bson.D{{
  2. "name",
  3. bson.D{{
  4. "$in",
  5. bson.A{"Alice", "Bob"}
  6. }}
  7. }}

The Raw family of types is used for validating a slice of bytes. You can also retrieve single elements from Raw types using a Lookup(). This is useful if you don't want the overhead of having to unmarshall the BSON into another type. This tutorial will just use the D family of types.

  1. func main(){
  2. // bson.D 是一组key-value的集合 有序
  3. d :=bson.D{
  4. {"Name","mark"},
  5. {"Age",12},
  6. }
  7. x :=d.Map() // 可以转为map
  8. fmt.Println(x)
  9. // bson.M是一个map 无序的key-value集合,在不要求顺序的情况下可以替代bson.D
  10. m :=bson.M{
  11. "name":"mark",
  12. "age":12,
  13. }
  14. fmt.Println(m)
  15. // bson.A 是一个数组
  16. a := bson.A{
  17. "jack","rose","jobs",
  18. }
  19. fmt.Println(a)
  20. // bson.E是只能包含一个key-value的map
  21. e :=bson.E{
  22. "name","mark",
  23. }
  24. fmt.Println(e)
  25. }

Normal usages

Test connection is valid or not

  1. //pingerr :=client.Ping(ctx,nil)
  2. pingerr :=client.Ping(ctx,readpref.Primary())
  3. if pingerr != nil{
  4. fmt.Println(pingerr)
  5. return
  6. }

Get database or collection

  1. c := client.Database("db_name").Collection("collection_name")

Drop collection

  1. collection.Drop(ctx)

CRUD Operations

Insert Documents

  1. insertOneRes, err := collection.InsertOne(ctx, data)
  2. //InsertMany

Select Documents

  1. // 查询单条数据
  2. err := collection.FindOne(ctx, bson.D{{"name", "howie_2"}, {"age", 11}}).Decode(&obj)
  3. // 查询单条数据后删除该数据
  4. err = collection.FindOneAndDelete(ctx, bson.D{{"name", "howie_3"}})
  5. // 询单条数据后修改该数据
  6. err = collection.FindOneAndUpdate(ctx, bson.D{{"name", "howie_4"}}, bson.M{"$set": bson.M{"name": "这条数据我需要修改了"}})
  7. // 查询单条数据后替换该数据
  8. FindOneAndReplace(ctx, bson.D{{"name", "howie_5"}}, bson.M{"hero": "这条数据我替换了"})
  9. // 一次查询多条数据(查询createtime>=3,限制取2条,createtime从大到小排序的数据)
  10. cursor, err = collection.Find(ctx, bson.M{"createtime": bson.M{"$gte": 2}}, options.Find().SetLimit(2), options.Find().SetSort(bson.M{``"createtime"``: -1}))
  11. // 查询数据数目
  12. Count

Update Document

  1. // 修改一条数据
  2. updateRes, err := collection.UpdateOne(ctx, bson.M{``"name"``: ``"howie_2"``}, bson.M{``"$set"``: bson.M{``"name"``: ``"我要改了他的名字"``}})
  3. // 修改多条数据
  4. updateRes, err = collection.UpdateMany(ctx, bson.M{``"createtime"``: bson.M{``"$gte"``: 3}}, bson.M{``"$set"``: bson.M{``"name"``: ``"我要批量改了他的名字"``}})

Delete Documents

  1. // 删除1条
  2. delRes, err = collection.DeleteOne(ctx, bson.M{``"name"``: ``"howie_1"``})
  3. // 删除多条
  4. delRes, err = collection.DeleteMany(getContext(), bson.M{``"createtime"``: bson.M{``"$gte"``: 7}})

go语言操作mongodb的更多相关文章

  1. GO学习-(26) Go语言操作mongoDB

    Go语言操作mongoDB mongoDB是目前比较流行的一个基于分布式文件存储的数据库,它是一个介于关系数据库和非关系数据库(NoSQL)之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的. ...

  2. 使用python语言操作MongoDB

    MongoDB是一个跨平台的NoSQL,基于Key-Value形式保存数据.其储存格式非常类似于Python的字典,因此用Python操作MongoDB会非常的容易. pymongo的两种安装命令 p ...

  3. Go操作MongoDB

    mongoDB是目前比较流行的一个基于分布式文件存储的数据库,它是一个介于关系数据库和非关系数据库(NoSQL)之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的. mongoDB介绍 mon ...

  4. 学习MongoDB--(11):应用举例(利用java操作MongoDB)

    原文地址:http://blog.csdn.net/drifterj/article/details/7948090 目录地址:http://blog.csdn.net/DrifterJ/articl ...

  5. Mongodb入门并使用java操作Mongodb

    转载请注意出处:http://blog.csdn.net/zcm101 最近在学习NoSql,先从Mongodb入手,把最近学习的总结下. Mongodb下载安装 Mongodb的下载安装就不详细说了 ...

  6. 使用Python操作MongoDB

    MongoDB简介(摘自:http://www.runoob.com/mongodb/mongodb-intro.html) MongoDB 由C++语言编写,是一个基于分布式文件存储的开源数据库系统 ...

  7. Python操作MongoDB看这一篇就够了

    MongoDB是由C++语言编写的非关系型数据库,是一个基于分布式文件存储的开源数据库系统,其内容存储形式类似JSON对象,它的字段值可以包含其他文档.数组及文档数组,非常灵活.在这一节中,我们就来看 ...

  8. Node操作MongoDB并与express结合实现图书管理系统

    Node操作MongoDB数据库 原文链接:http://www.xingxin.me/ Web应用离不开数据库的操作,我们将陆续了解Node操作MongoDB与MySQL这是两个具有代表性的数据库, ...

  9. 在ASP.NET Core2上操作MongoDB就是能这么的简便酷爽(自动完成分库分表)

    NoSQL是泛指非关系型的数据库,现今在我们的项目中也多有使用,其独特的优点为我们的项目架构带来了不少亮点,而我们这里的主角(MongoDB)则是NoSQL数据库家族中的一种.事实上,NoSQL数据库 ...

随机推荐

  1. linux命令系列 ls

    ls是linux中最常用的命令之一 ls 的功能是list directory contents,其常用的选项如下: (1) -l   use a long listing format(长格式,显示 ...

  2. (第九周)Beta-1阶段成员贡献分

    项目名:食物链教学工具 组名:奋斗吧兄弟 组长:黄兴 组员:李俞寰.杜桥.栾骄阳.王东涵 个人贡献分=基础分+表现分 基础分=5*5*0.5/5=2.5 成员得分如下: 成员 基础分 表现分 个人贡献 ...

  3. Maven教程--02设置Maven本地仓库|查看Maven中央仓库

    一:设置Maven本地仓库 Maven默认仓库的路径:~\.m2\repository,~表示我的个人文档:例如:C:\Users\Edward\.m2\repository:如下图: Maven的配 ...

  4. slf4j+log4j的初次使用

    关于这两者的组合应用带来的好处,google都有 就不说了. 首先说下配置, 工作笔记:在myeclipse 中创建一个java project 创建一个 TestSlf4J 类 package co ...

  5. “吃神么,买神么”的第一个Sprint计划(第四天)

    “吃神么,买神么”项目Sprint计划 ——5.24  星期日(第四天)立会内容与进度 摘要:logo做出来了,但是在立会展示时遭到反对,不合格,重新设计.(附上失败的logo图) 目前搜索栏出来了, ...

  6. 使用java开发微信公众平台(1)

    目录 开发服务器 域名验证 获取access_token 自定义菜单 个人账号不能定义url访问服务器,使用测试号就不用认证添加url了,进入公众平台测试账号 开发服务器 域名验证 进入公众平台测试账 ...

  7. 代码上传不到github远程仓库的经历和总结

    第二次的作业是分布式版本控制系统Git的安装与使用.一切都好端端地进行,知道最后的上传到给远程仓库时一直都上传失败.舍友也过来调试和助教的指导,依然不成功.我也上网进行了大量的翻查资料也未能成功.这是 ...

  8. AVL树/线索二叉树

    此文转载: http://www.cnblogs.com/skywang12345/p/3577360.html AVL树是一棵特殊的高度平衡的二叉树,每个节点的两棵子树高度最大差为1.所以在每次的删 ...

  9. sql%bulk_rowcount && sql%rowcount 的使用

    说明: %BULK_ROWCOUNT 属性计算FORALL迭代影响行数 在进行SQL数据操作语句时,SQL引擎打开一个隐式游标(命名为SQL),该游标的标量属性(scalar attribute)有 ...

  10. java 自定义异常的回顾

    一.异常的分类: 1.编译时异常:编译时被检测的异常 (throw后,方法有能力处理就try-catch处理,没能力处理就必须throws).编译不通过,检查语法(其实就是throw和throws的配 ...