golang访问MongoDB数据库
2023-09-27 14:22:02 时间
最常用的第三方驱动
package main
import (
"fmt"
_ "github.com/sbunce/bson"
"gopkg.in/mgo.v2"
"labix.org/v2/mgo/bson"
)
//type Student struct {
//Name string `bson: "name"`
//Age int `bson: "age"`
//Sid string `bson: "sid"`
//Status int `bson: "status"`
//}
type Student struct {
Name string
Age int
Sid string
Status int
}
type Per struct {
Per []Student
}
var (
ip = "172.17.0.3"
)
func main() {
fmt.Println("vim-go")
b := insert()
fmt.Printf("插入数据,%v\n", b)
b = findOne()
b = findAll()
}
func insert() bool {
mongo, err := mgo.Dial(ip) // 建立连接
defer mongo.Close()
if err != nil {
return false
}
client := mongo.DB("mydb_tutorial").C("t_student") //选择数据库和集合
//创建数据
data := Student{
Name: "学习MongoDB的第一课",
Age: 18,
Sid: "learn_001",
Status: 1,
}
//插入数据
cErr := client.Insert(&data)
if cErr != nil {
return false
}
return true
}
func findOne() bool {
mongo, err := mgo.Dial(ip)
defer mongo.Close()
if err != nil {
return false
}
client := mongo.DB("mydb_tutorial").C("t_student")
user := Student{}
//查找sid为 s20180907
cErr := client.Find(bson.M{"sid": "learn_001"}).One(&user)
if cErr != nil {
return false
}
fmt.Println(user)
return true
}
func findAll() bool {
mongo, err := mgo.Dial(ip)
defer mongo.Close()
if err != nil {
return false
}
client := mongo.DB("mydb_tutorial").C("t_student")
//每次最多输出15条数据
iter := client.Find(bson.M{"status": 1}).Sort("_id").Skip(1).Limit(15).Iter()
var stu Student
var users Per
for iter.Next(&stu) {
users.Per = append(users.Per, stu)
}
if err := iter.Close(); err != nil {
return false
}
fmt.Println(users)
return true
}
//func update() bool {
//mongo, err := mgo.Dial("192.168.0.91")
//defer mongo.Close()
//if err != nil {
//return false
//}
//client := mongo.DB("mydb_tutorial").C("t_student")
////只更新一条
//cErr := client.Update(bson.M{"status": 1}, bson.M{"$set": bson.M{"age": 20}})
//if cErr != nil {
//return false
//}
//return true
//}
//func del() bool {
//mongo, err := mgo.Dial("192.168.0.91")
//defer mongo.Close()
//if err != nil {
//return false
//}
//client := mongo.DB("mydb_tutorial").C("t_student")
////只更新一条
//cErr := client.Remove(bson.M{"sid": "s20180907"})
//if cErr != nil {
//return false
//}
//return true
//}
MongoDB官方驱动
package main
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// You will be using this Trainer type later in the program
type Trainer struct {
Name string
Age int
City string
}
func main() {
// Rest of the code will go here
// Set client options 设置连接参数
clientOptions := options.Client().ApplyURI("mongodb://172.17.0.3:27017")
// Connect to MongoDB 连接数据库
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
// Check the connection 测试连接
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
collection := client.Database("test").Collection("trainers")
ash := Trainer{"Ash", 10, "Pallet Town"}
misty := Trainer{"Misty", 10, "Cerulean City"}
brock := Trainer{"Brock", 15, "Pewter City"}
insertResult, err := collection.InsertOne(context.TODO(), ash)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted a single document: ", insertResult.InsertedID)
// 插入多个文档数据
trainers := []interface{}{misty, brock}
insertManyResult, err := collection.InsertMany(context.TODO(), trainers)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs)
// 更新文档
filter := bson.D{{"name", "Ash"}}
// 年龄加1,$inc 可能是运算符
update := bson.D{
{"$inc", bson.D{
{"age", 1},
}},
}
updateResult, err := collection.UpdateOne(context.TODO(), filter, update)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)
// 查找Find
// create a value into which the result can be decoded
var result Trainer
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found a single document: %+v\n", result)
// 查找多个文档
// Pass these options to the Find method,指定查询记录的条数
findOptions := options.Find()
findOptions.SetLimit(2)
// Here's an array in which you can store the decoded documents
var results []*Trainer
// Passing bson.D{{}} as the filter matches all documents in the collection
// bson.D{{}} 相当没有条件
cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)
if err != nil {
log.Fatal(err)
}
// Finding multiple documents returns a cursor
// Iterating through the cursor allows us to decode documents one at a time
// 通过游标遍历记录
for cur.Next(context.TODO()) {
// create a value into which the single document can be decoded
var elem Trainer
err := cur.Decode(&elem)
if err != nil {
log.Fatal(err)
}
results = append(results, &elem)
}
if err := cur.Err(); err != nil {
log.Fatal(err)
}
// Close the cursor once finished
cur.Close(context.TODO())
fmt.Printf("Found multiple documents (array of pointers): %+v\n", results)
// 删除所有的记录
deleteResult, err := collection.DeleteMany(context.TODO(), bson.D{{}})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult.DeletedCount)
// 断开连接
err = client.Disconnect(context.TODO())
if err != nil {
log.Fatal(err)
}
fmt.Println("Connection to MongoDB closed.")
}
相关文章
- 十分钟了解Mongodb数据库
- MongoDB 事务,复制和分片的关系
- mongodb获取配置参数getParameter
- mongodb的用户管理
- 从炉石传说数据库故障谈谈MongoDB的数据库备份和恢复手段
- 攻击敲诈不耽误,一周拿下2.7万MongoDB数据库
- MongoDB分布式文件存储系统
- [Android+LBS] LBS based on Symfony2 & MongoDB
- 线上mongodb 数据库用户到期时间修改的操作记录
- MongoDB 基础
- 下载 | 勒索软件又攻击MongoDB数据库 2.6万台服务器4.5万个数据库被加密
- MongoDB(课时29 MapReduce)
- MongoDB(课时9 范围运算)
- MongoDB(课时22 过期索引)
- nagios监控mongodb
- mongodb分片集群运维管理
- 【MongoDB】windows平台搭建Mongo数据库复制集(相似集群)(一)
- MongoDB---性能优化---(1)
- 【Redis】NoSQL 数据库 ② ( NoSQL 数据库特点 | NoSQL 数据库适用场景 | 常见的 NoSQL 数据库 | Redis | MongoDB | 数据库排名 )
- MongoDB数据库的密码和权限问题
- nodejs+express+mongodb简单的例子
- PHP操作MongoDB 数据库
- MongoDB创建与删除数据库
- Linux下安装MongoDB 4.2数据库--使用网络yum方式
- Python访问MongoDB数据库
- 数据库:mongodb与关系型数据库相比的优缺点zz (转)
- MongoDB设置为Windows服务