博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
go语言操作mongodb
阅读量:4671 次
发布时间:2019-06-09

本文共 5365 字,大约阅读时间需要 17 分钟。

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:

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

Example code

package mainimport (    "context"    //"encoding/json"    "fmt"    "github.com/mongodb/mongo-go-driver/bson"    "github.com/mongodb/mongo-go-driver/mongo"    "github.com/mongodb/mongo-go-driver/mongo/options"    "log"    "time")func main() {    // 连接数据库    ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)  // ctx    opts := options.Client().ApplyURI("mongodb://localhost:27017")  // opts    client, _ := mongo.Connect(ctx,opts)  // client    // 使用    db := client.Database("mark")  // database    stu := db.Collection("student") // collection        // 插入数据   直接使用student struct实例    xm := Student{Name:"小明",Age:17,Sex:M,}    res, _ := stu.InsertOne(ctx,xm)        // 查询数据  bson.D{}创建查询条件    cur, err := stu.Find(ctx, bson.D{})  // find       CheckError(err)        // 延时关闭游标    defer cur.Close(ctx)    for cur.Next(ctx) {            // 可以decode到bson.M  也就是一个map[string]interface{}中        // 也可以直接decode到一个对象中        s := &Student{}        var result bson.M        err := cur.Decode(&result) // decode 到map        err = cur.Decode(s)  // decode 到对象        CheckError(err)                // do something with result....        // 可以将map 或对象序列化为json        //js ,_:=json.Marshal(result)        //json.Unmarshal(js,s) //反学序列化回来        fmt.Println(s)    }}type Gender uint8const (    M = iota    F)type Student struct {    Name string `json:"name"`    Age int `json:"age"`    Sex Gender `json:"gender"`}func CheckError( err error){    if err != nil {        log.Println(err.Error())        return    }}

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:

bson.D{
{ "name", bson.D{
{ "$in", bson.A{"Alice", "Bob"} }}}}

The Raw family of types is used for validating a slice of bytes. You can also retrieve single elements from Raw types using a . 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.

func main(){    // bson.D 是一组key-value的集合  有序     d :=bson.D{        {"Name","mark"},        {"Age",12},    }    x :=d.Map() // 可以转为map    fmt.Println(x)        // bson.M是一个map 无序的key-value集合,在不要求顺序的情况下可以替代bson.D    m :=bson.M{        "name":"mark",        "age":12,    }    fmt.Println(m)    // bson.A 是一个数组    a := bson.A{        "jack","rose","jobs",    }    fmt.Println(a)    // bson.E是只能包含一个key-value的map    e :=bson.E{        "name","mark",    }    fmt.Println(e)}

Normal usages

Test connection is valid or not

//pingerr :=client.Ping(ctx,nil)    pingerr :=client.Ping(ctx,readpref.Primary())    if pingerr != nil{        fmt.Println(pingerr)        return    }

Get database or collection

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

Drop collection

collection.Drop(ctx)

CRUD Operations

Insert Documents

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

Select Documents

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

Update Document

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

Delete Documents

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

转载于:https://www.cnblogs.com/endurance9/p/10409232.html

你可能感兴趣的文章
Meta http-equiv属性详解
查看>>
python字符串,列表常用操作
查看>>
阅读笔记06
查看>>
《http权威指南》读书笔记14
查看>>
2019 COMPSYS 302 Class Protocol V6
查看>>
win7主机与linux虚拟机共享方法之右键添加Sharing Options
查看>>
网友写的验证码生成方案,可防止绝大多数机械识别。
查看>>
8 个最好的 jQuery 树形 Tree 插件
查看>>
软件质量与测试 黑盒测试
查看>>
Salesforce.com + AutoCAD WS集成研究集锦
查看>>
Office 2007在安装过程中出错
查看>>
浅析Hibernate映射(五)——集合映射
查看>>
java.lang.ClassNotFoundException: com.sun.xml.ws.spi.ProviderImpl解决办法
查看>>
检测到在集成的托管管道模式下不适用的ASP.NET设置的解决方法(非简单设置为【经典】模式)。 - CatcherX...
查看>>
Bitmap处理
查看>>
C语言记录汇总
查看>>
webservices系列(三)——调用线上webservice(天气预报和号码查询)
查看>>
callback 模式
查看>>
什么是servlet
查看>>
Something about TFS
查看>>