当前位置:网站首页>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”,它会自动创建
由于基础知识占了很大篇幅,所以仅展示了一些最基础的知识。后面计划用一个星期把常用的增删改查过一遍,记录下来。因为百度真的没啥具体的演示代码。
边栏推荐
- Leetcode 1208. Try to make the strings equal as much as possible (finally solved, good night)
- 2022年烷基化工艺考题及模拟考试
- 解决使用Exception抛出后,@Transactional不生效
- Getting started with tensorflow
- PTA:7-63 计算高考状元
- Pytorch---Pytorch进行自定义Dataset
- Pta:6-71 clock simulation
- Please use the NLTK Downloader to obtain the resource
- PTA:7-60 宠物的生长
- 【一起上水硕系列】Day Three - preview4
猜你喜欢

Deploying Apache pulsar on kubesphere

There is a problem with redis startup

Xiaojinwei, chairman of Chenglian Technology: implement the national strategy of data economy and lead the development of new consumption in the digital era!

【一起上水硕系列】Day Three - preview4

应急响应-hw复习

众昂矿业:新能源新材料产业链对萤石需求大增

How to ensure application security

Analysis on the current situation of the Internet of things in 2022

Avltree - arbre de recherche binaire équilibré

【Pytorch】用自动微分求sin(x)的导数
随机推荐
解决使用Exception抛出后,@Transactional不生效
leetcode 91. Decode Ways 解码方法(中等)
Leetcode 1208. Make strings as equal as possible
2022年烷基化工艺考题及模拟考试
If you want to understand PostgreSQL, you must first brush the architecture
leetcode 91. Decode ways (medium)
Svg+js smart home monitoring grid layout
PTA:7-87 集合的模拟实现(类模板)
PTA:7-85 数据的间距问题(重载+函数模板)
深度学习 TensorFlow入门
Can MySQL be used in Linux
PTA:7-86 集合的模拟实现(函数模板)
Pytoch --- pytoch customizes the dataset
PTA:6-29 虚基类的应用-人与教师学生
PTA:7-65 饮料的价格
[binary tree] flip equivalent binary tree
Introduction and use of MySQL view
【Pytorch】用自动微分求sin(x)的导数
After Huawei online battle service players quickly match, different players receive different lists of players in the same room
Online JSON to CSharp (c) class tool