当前位置:网站首页>golang使用mongo-driver操作——增(基础)
golang使用mongo-driver操作——增(基础)
2022-06-23 03:50:00 【lsjweiyi】
以5.0为基本,mongo常用数据类型与golang数据类型的对应:
| 类型 | 描述 | 代码 | golang中对应类型 |
|---|---|---|---|
| Double | 双精度浮点 | 1 | float64 |
| String | 字符串 | 2 | string |
| Object | 对象类型 | 3 | struct |
| Array | 数组 | 4 | 数组 |
| Binary data | 二进制数组 | 5 | []byte |
| ObjectId | mongo中自动生成的主键_id类型 | 7 | primitive.ObjectID(本质是[12]byte) |
| Boolean | 布尔 | 8 | bool |
| Date | 日期 | 9 | time.Time |
| Null | null | 10 | nil |
| Regular Expression | 正则表达式 | 11 | 正则表达式 |
| 32-bit integer | 32为整形 | 16 | int32 |
| 64-bit integer | 64位整形 | 18 | int64 |
mongo完整数据类型
上面的代码是在mongo中做类型判断时可以使用的表示形式。当然也可以用字符串,推荐使用数字吧,简单点。
bson
首先,我们得知道,mongo的数据是json形式的,但是在json的基础上,它丰富了数据类型,所以叫做了bson。这是最基本的数据结构。
后面可以发现我们在代码大量用到bson.M,看了代码下来应该能理解了,其实就是构造了类似于map的东西,用于封装成mongo理解的数据。但是我们多数使用了M,实际上还有几个,他们的作用和区别:
M
是一个无序的bson对象。用法也和map很像。在数据对顺序不敏感的时候,优先使用它。
D
有序的bson对象,和M的本质区别就是对顺序敏感。用法稍有不同,M用冒号,它用逗号,用它比较烦,大括号很多层。不过也是有必要的。
A
有序的bson数组,当需要数组时,它作为容器去包围M和D。
E
不怎么用,官方都说用D代替使用,所以不需要了解吧。
连接数据库
首先得在admin数据库中创建角色,篇幅有限,就不写过程了
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func GetMongo() (*mongo.Database, error) {
credential := options.Credential{
AuthMechanism: "SCRAM-SHA-256",
Username: "admin",
Password: "123456",
AuthSource: "admin",
}
clientOpts := options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%d", "127.0.0.1", 27017)).SetAuth(credential)
var ctx = context.TODO()
client, err := mongo.Connect(ctx, clientOpts)
if err != nil {
return nil, err
}
// Check the connection
err = client.Ping(ctx, nil)
if err != nil {
return nil, err
}
mongodb := client.Database("test")
return mongodb, nil
}
}
新增
新增的代码
import (
"context"
"fmt"
"time"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
// 有常见的类型
type BaseAdd struct {
Id int
Int32 int32
Int64 int64
Float32 float32
Float64 float64
Text string
Boolean bool
ByteList []byte
StringList []string
Date time.Time
ObjectID primitive.ObjectID
}
// 最基本的新增一条数据
func (a1 *BaseAdd) Add(mongo *mongo.Database, ctx context.Context) error {
result, err := mongo.Collection("test").InsertOne(ctx, a1)
fmt.Println(result.InsertedID) // 会返回主键_id的值
return err
}
// 插入多条数据
func AddMany(mongo *mongo.Database, ctx context.Context, data ...interface{
}) {
result, err := mongo.Collection("test").InsertMany(ctx, data)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(result.InsertedIDs...) //返回的是主键数组
}
调用接口
func Base(mongo *mongo.Database, ctx context.Context) {
// 初始化一个包含常见类型的结构体,保存到mongo看看
baseAdd1 := BaseAdd{
Id: math.MaxInt,
Int32: math.MaxInt32,
Int64: math.MaxInt64,
Float32: math.MaxFloat32,
Float64: math.MaxFloat64,
Text: "hello1",
Boolean: true,
ByteList: []byte{
'a', 'b', 'c', 'd', 'e'},
StringList: []string{
"test1", "test2", "test3"},
Date: time.Now(),
ObjectID: primitive.NewObjectID(),
}
baseAdd1.Add(mongo, ctx)
baseAdd2 := BaseAdd{
Id: math.MaxInt - 1,
Int32: math.MaxInt32 - 1,
Int64: math.MaxInt64 - 1,
Float32: math.MaxFloat32 - 1,
Float64: math.MaxFloat64 - 1,
Text: "hello2",
Boolean: false,
ByteList: []byte{
'c', 'd', 'e', 'f', 'g'},
StringList: []string{
"test3", "test4", "test5"},
Date: time.Now(),
ObjectID: primitive.NewObjectID(),
}
AddMany(mongo, ctx, baseAdd1, baseAdd2)
}
打印结果
D:\workSpace\go\mongo>go run main.go
ObjectID("62b074a9b207419896a53cdf")
ObjectID("62b074a9b207419896a53ce1") ObjectID("62b074a9b207419896a53ce2")
使用robot 3T 看的结果,如愿创建了三条数据:
展开其中一条看看:
后面一栏就是存在mongo中的类型,可以清晰地看到,golang中的数据类型存到mongo中的样子
再看看json格式的效果:
{
"_id" : ObjectId("62b07d4ac1e231479c955df7"),
"id" : NumberLong(9223372036854775807),
"int32" : NumberInt(2147483647),
"int64" : NumberLong(9223372036854775807),
"float32" : 340282346638528860000000000000000000000.0,
"float64" : 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0,
"text" : "hello1",
"boolean" : true,
"bytelist" : BinData(0, "YWJjZGU="),
"stringlist" : [
"test1",
"test2",
"test3"
],
"date" : ISODate("2022-06-20T13:59:38.921+0000"),
"object" : {
"id" : NumberInt(1),
"text" : "你好"
},
"objectid" : ObjectId("62b07d4ac1e231479c955df6")
}
这里就有几个细节:
- golang中的int类型会根据平台的不同转化为对应的32位或64位
- go中float都是用double类型存储
- go的byte数组存到mongo中就是BinData类型,也就是Binary data
- 仔细观察
ObjectID和_id,发现我们调用函数生成id和系统生成的是一样格式的,意味着可以主动生成该id。 - 观察
ObjectID,go中字段的大写,在mongo中会被全部转化为小写,当然也可以使用tagbson:"objectID"去人为标注,并且推荐各平台使用统一的命名方式,目前还未发现驱动能够为我们自动设置驼峰等命名规范。 - 在insert的时候,我并没有主动创建集合“test”,它会自动创建
由于基础知识占了很大篇幅,所以仅展示了一些最基础的知识。后面计划用一个星期把常用的增删改查过一遍,记录下来。因为百度真的没啥具体的演示代码。
边栏推荐
- svg d3. JS generate tree tree view
- Inscription of lougu brush
- PTA:7-64 该日是该年的第几天
- [learn FPGA programming from scratch -40]: Advanced - Design - competition and risk
- PTA:6-71 时钟模拟
- Pta:7-85 data spacing (overload + function template)
- Leetcode 1208. 尽可能使字符串相等
- Leetcode 1208. Make strings as equal as possible
- Common interview questions in automated testing
- Pytorch---使用Pytorch的预训练模型实现四种天气分类问题
猜你喜欢

Cool mouse following animation JS plug-ins 5

抖音x-bogus和_signature参数分析

JVM调优简要思想及简单案例-为什么需要JVM调优?

x24Cxx系列EEPROM芯片C语言通用读写程序

制造型企业开发的SRM供应商管理系统特点是什么

x64dbg 基本使用技巧

What are the characteristics of SRM supplier management system developed by manufacturing enterprises

Please use the NLTK Downloader to obtain the resource

Avltree - arbre de recherche binaire équilibré

【深度学习】深度学习推理框架 TensorRT MNN OpenVINO ONNXRuntime
随机推荐
Zhongang Mining: the demand for fluorite in the new energy and new material industry chain has increased greatly
How does flutter achieve different zoom animation effects
Basic skills of x64dbg
x24Cxx系列EEPROM芯片C语言通用读写程序
Cocos学习日记1——节点
Svg+js smart home monitoring grid layout
Pytoch --- pytoch customizes the dataset
[deep learning] deep learning reasoning framework tensorrt MNN openvino onnxruntime
靜態查找錶和靜態查找錶
麦肯锡:2021年量子计算市场投资增长强劲,人才缺口扩大
PTA:7-37 学号解析
It supports running in kubernetes, adds multiple connectors, and seatunnel version 2.1.2 is officially released!
Dynamics 365 插件中权限操作
Pta:6-29 application of virtual base classes - people, teachers and students
PTA:7-69 数据的间距问题
Pta:6-71 clock simulation
Pytoch --- use pytoch's pre training model to realize four weather classification problems
[pytoch] calculate the derivative of sin (x) by automatic differentiation
2022年烷基化工艺考题及模拟考试
[Shangshui Shuo series] day three - preview4