吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1682|回复: 5
收起左侧

[其他转载] go-mongodb 笔记

[复制链接]
XMQ 发表于 2021-8-10 14:33
最近用到了mongodb数据库,在此记录下基本操作和知识点

mongodb  --- nosql  数据库,一般被用来存储聊天,新闻,博客等含有复杂结构的数据。

1. 下载,安装(百度)

2. 一些基本命令

显示数据库 show dbs  /   show databases
切换数据库 use  xxxx
查看数据库中的数据集(表) show collections
查看数据集中的数据
db.表名.find()
查看指定数据 db.表名.find({key:value})  
db.表名.find({key:value}).count()   查看数量

db.表名.find({key:value}).length()   查看数量
删除 db.student.deleteOne(doc)     删除一个
db.student.deleteMany(doc)    删除多个
remove({}) 全部删除
...... 其他推荐看官方文档
3. 用 go 来操作
     首先,下载相关的依赖
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"

     接着,连接数据库,调用mongo.Connect 方法
func ConnectToDB(url,name string,timeout time.Duration,num uint64)(*mongo.Database,error){
   ctx, cancel := context.WithTimeout(context.Background(), timeout)  // 连接超时

   defer cancel()

   o := options.Client().ApplyURI(url)

   o.SetMaxPoolSize(num)   // 连接做大数量

   client, err := mongo.Connect(ctx, o)

   if err != nil {

      return nil, err

   }

   return client.Database(name), nil

}
myClient, err := ConnectToDB("mongodb://127.0.0.1:27017","bigdata",10,100)
也可以用client.Ping 方法来测试连接是否成功
err = client.Ping(context.TODO(), nil)if err != nil {
   log.Println("数据库连接失败")
   return
}
连接成功后,接下来是插入数据
在插入之前,先定义要插入的结构体
type Student struct {     Id  string `json:"id" bson:"_id"`  // 返回_id (


   Name string

   Age int

}
如果你的结构体没有此字段,是不会返回_id)_id: 是mongodb在每插入一条数据时自动生成唯一的一个标识符,它前4个字节表示时间戳,接着3位是机器识别码,之后2位是进程的pid值,最后3位是随机数
[/table]
插入一条数据
s1 := Student{"xiaoming",20}
insertResult, err := collection.InsertOne(context.TODO(), s1)
插入多条数据
s3 := s1
students := []interface{}{s2, s3}

insertManyResult, err := collection.InsertMany(context.TODO(), students)
查找数据
[table]
filter := bson.D{{"title","python5555"}}  创建一个过滤条件


err =  collection.FindOne(context.TODO(),filter).Decode(&article)
查找单条数据
cur,err := collection.Find(context.TODO(),filter) 查找多条数据
###注意,查询多条返回的是一个游标,我们得通过cur.next() 方法把数据循环遍历出来
  find := options.Find()
find.SetLimit(3)  // 限制返回多少条数据

cur,err := collection.Find(context.TODO(),filter)

//  cur  是一个游标,然后通过next遍历出来

for cur.Next(context.TODO()){

   var el = article  // 自定义

   err := cur.Decode(&el)

   if err != nil {

      fmt.Println("查找失败")

   }

   fmt.Println("el",el)

   article2 = append(article2,el)

}

defer cur.Close(context.TODO())  // 最后关闭游标
更新  (通过filter来更新)
updateResult, err := collection.UpdateMany(context.TODO(),filter,update)  // 更新多条数据
collection.UpdateOne() // 更新一条
collection.UpdateByID()  // 通过_id来更新

删除
deleteResult, err := collection.DeleteMany(context.TODO(), filter) // 返回删除的条数

还有其他很多功能,感兴趣的小伙伴上github看文档
补充一个通过_id来查找数据
oid ,err:= primitive.ObjectIDFromHex("61109dc7793ae6be4483f96a");
filter2 :=bson.M{"_id":oid}
var article rep.ArticleList
err = collection.FindOne(context.TODO(),filter2).Decode(&article)
if err != nil {
   fmt.Println("查找失败")
}
先获取_id,然后通过primitive.ObjectIDFromHex("")方法获取ObjectID,在创建过滤器来查找就行
~~~~~~~~~end~~~~~~~~~~~~~~~~

免费评分

参与人数 1吾爱币 +1 热心值 +1 收起 理由
Seven_2017 + 1 + 1 我很赞同!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

aLong2016 发表于 2021-8-19 15:41
我一直没接触过mongo
lf1988103 发表于 2021-10-14 09:08
我有2个问题,请教下
1.怎么查询过滤有时候用的是bson.M ,有时候有用的是bson.D 有啥区别吗?
2.type Student struct {     Id  string `json:"id" bson:"_id"`  // 返回_id  这个 Id 不应该设置成bson.ObjectId类型吗?
 楼主| XMQ 发表于 2021-10-14 19:10
lf1988103 发表于 2021-10-14 09:08
我有2个问题,请教下
1.怎么查询过滤有时候用的是bson.M ,有时候有用的是bson.D 有啥区别吗?
2.type St ...

在源码上看
bson.D中的D 是这么解释的: D is an ordered representation of a BSON document. This type should be used when the order of the elements matters, (D是BSON文档的有序表示形式。当元素顺序重要时,应使用此类型)
bson.M中的M:M is an unordered representation of a BSON document. This type should be used when the order of the elements does not (M是BSON文档的无序表示。当元素顺序不一致时,应使用此类型)
第二个还没试过

steven666 发表于 2022-7-28 11:26
非常不错
yangyoucai 发表于 2022-8-2 13:39
谢谢分享,收藏学习
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-4-28 05:51

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表