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 main

import (
"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 uint8
const (
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 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.

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}})

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. 2019 年软件开发人员必学的编程语言 Top 3

    AI 前线导读:这篇文章将探讨编程语言世界的现在和未来,这些语言让新一代软件开发者成为这个数字世界的关键参与者,他们让这个世界变得更健壮.连接更加紧密和更有意义.开发者要想在 2019 年脱颖而出,这 ...

  2. 【RL系列】马尔可夫决策过程中状态价值函数的一般形式

    请先阅读上一篇文章:[RL系列]马尔可夫决策过程与动态编程 在上一篇文章里,主要讨论了马尔可夫决策过程模型的来源和基本思想,并以MAB问题为例简单的介绍了动态编程的基本方法.虽然上一篇文章中的马尔可夫 ...

  3. kali vmtools 不能复制粘贴解决方法(绝对实用)

    朋友问起怎么vm kali 2019怎么不能复制了,而且网上的方法大多不适合.我就在这儿记录一笔吧,方便大家. 之前发现最新kali复制粘贴不能用,后来发现一个奇妙的套路,不是共享文件夹.只需要把文件 ...

  4. iframe子页面position的fixed

    前言: 首先说一说我昨天天的苦逼经历.中午吃饭时一同事跟我说,他做的项目嵌套iframe后,子页面的position设置fixed失效了. 经过反复询问,得知他用了两层iframe,再加上最外的父页面 ...

  5. 安装macOS Sierra后怎么找回“任何来源”选项

    安装macOS Sierra后,会发现系统偏好设置的“安全与隐私”中默认已经去除了允许“任何来源”App的选项,无法运行一些第三方应用(提示xx.app已经损坏).如果需要恢复允许“任何来源”的选项, ...

  6. 哪些场景下无法获得上一页referrer信息

    哪些场景下无法获得上一页referrer信息 直接在浏览器地址栏中输入地址: 使用 location.reload() 刷新(location.href 或者  location.replace()  ...

  7. 第二阶段Sprint冲刺会议2

     进展:讨论主界面布局,跳转界面的布局,查看有关页面跳转的资料及示例代码并试着编写. 

  8. 浅谈GIT

    浅谈GIT: 牛老师提出的git,于我而言,是一个陌生和新鲜的词汇,在此之前我从未听过git,按照老师的要求,我去搜索了关于git的介绍,有些看懂了,但大部分还是不懂得,在介绍中我了解git其实之前使 ...

  9. caffe可视化模型

    进入$CAFFE_ROOT/python: $ python draw_net.py ../models/bvlc_reference_caffenet/train_val.prototxt caff ...

  10. 使用pt-query-digest,找到不是很合适的sql

    pt-query-digest 1.  概述 索引可以我们更快速的执行查询,但是肯定存在不合理的索引,如果想找到那些索引不是很合适的查询,并在它们成为问题前进行优化,则可以使用pt-query-dig ...