安装mongo-driver
go get go.mongodb.org/mongo-driver
创建main.go
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://localhost: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!")
**断开连接 **
err = client.Disconnect(context.TODO())
if err != nil {
log.Fatal(err)
}
fmt.Println("Connection to MongoDB closed.")
目录结构
drivers/mongo.go
/**
* @Author : jinchunguang
* @Date : 19-11-5 下午3:07
* @Project : go-mongo
*/
package drivers
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
)
type MongoDrivers struct {
Client *mongo.Client
Database string
}
var MgoClient *mongo.Client
var MgoDbName string
// 初始化
func Init() {
MgoClient=Connect()
MgoDbName="test"
}
// 连接
func Connect() *mongo.Client {
// 设置客户端参数
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// 连接到MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
//defer client.Disconnect(context.TODO())
if err != nil {
log.Fatal(err)
}
// 检查链接
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
return client
}
// 关闭
func Close() {
err :=MgoClient.Disconnect(context.TODO())
if err != nil {
log.Fatal(err)
}
fmt.Println("Connection to MongoDB closed.")
}%
models/mgo_model.go
/**
* @Author : jinchunguang
* @Date : 19-11-5 下午2:59
* @Project : go-mongo
*/
package models
import (
"context"
"fmt"
_ "fmt"
"go-mongo/drivers"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
"strconv"
"time"
)
// 集合名称
const TrainerCollectionName = "trainer"
// TrainerModel
type Mgo struct {
collection *mongo.Collection
}
// NewTrainer
func NewMgo() *Mgo {
mgo := new(Mgo)
mgo.collection = drivers.MgoClient.Database(drivers.MgoDbName).Collection(TrainerCollectionName)
return mgo
}
// 插入单个
func (m *Mgo) InsertOne(document interface{}) (insertResult *mongo.InsertOneResult) {
insertResult, err := m.collection.InsertOne(context.TODO(), document)
if err != nil {
fmt.Println(err)
}
return
}
// 插入多个
func (m *Mgo) InsertMany(documents []interface{}) (insertManyResult *mongo.InsertManyResult) {
insertManyResult, err := m.collection.InsertMany(context.TODO(), documents)
if err != nil {
fmt.Println(err)
}
return
}
// 查询单个
func (m *Mgo) FindOne(key string, value interface{}) *mongo.SingleResult {
filter := bson.D{{key, value}}
singleResult := m.collection.FindOne(context.TODO(), filter)
if singleResult != nil {
fmt.Println(singleResult)
}
return singleResult
}
// 查询count总数
func (m *Mgo) Count() (string, int64) {
name := m.collection.Name()
size, _ := m.collection.EstimatedDocumentCount(context.TODO())
return name, size
}
// 按选项查询集合
// Skip 跳过
// Limit 读取数量
// Sort 排序 1 倒叙 , -1 正序
func (m *Mgo) FindAll(Skip, Limit int64, sort int) *mongo.Cursor {
SORT := bson.D{{"_id", sort}}
filter := bson.D{{}}
// where
findOptions := options.Find()
findOptions.SetSort(SORT)
findOptions.SetLimit(Limit)
findOptions.SetSkip(Skip)
cur, err := m.collection.Find(context.TODO(), filter, findOptions)
if err != nil {
fmt.Println(err)
}
return cur
}
// 获取集合创建时间和编号
func (m *Mgo) ParsingId(result string) (time.Time, uint64) {
temp1 := result[:8]
timestamp, _ := strconv.ParseInt(temp1, 16, 64)
dateTime := time.Unix(timestamp, 0) // 这是截获情报时间 时间格式 2019-04-24 09:23:39 +0800 CST
temp2 := result[18:]
count, _ := strconv.ParseUint(temp2, 16, 64) // 截获情报的编号
return dateTime, count
}
// 删除
func (m *Mgo) Delete(key string, value interface{}) int64 {
filter := bson.D{{key, value}}
count, err := m.collection.DeleteOne(context.TODO(), filter, nil)
if err != nil {
fmt.Println(err)
}
return count.DeletedCount
}
// 删除多个
func (m *Mgo) DeleteMany(key string, value interface{}) int64 {
filter := bson.D{{key, value}}
count, err := m.collection.DeleteMany(context.TODO(), filter)
if err != nil {
fmt.Println(err)
}
return count.DeletedCount
}
// 更新一个
func (m *Mgo) UpdateOne(key string, value interface{}, update interface{}) (updateResult *mongo.UpdateResult) {
filter := bson.D{{key, value}}
updateResult, err := m.collection.UpdateOne(context.TODO(), filter, update)
if err != nil {
log.Fatal(err)
}
return updateResult
}%
main.go
/**
* @Author : jinchunguang
* @Date : 19-11-5 下午2:50
* @Project : go-mongo
*/
package main
import (
"context"
"fmt"
"go-mongo/drivers"
"go-mongo/models"
"go.mongodb.org/mongo-driver/bson"
"log"
)
type Trainer struct {
Name string
Age int
City string
}
func main() {
// 初始化数据库
drivers.Init()
// 单个插入
ash := Trainer{"Ash", 10, "Pallet Town"}
InsertOneResult := models.NewMgo().InsertOne(ash)
fmt.Println("Inserted a single document: ", InsertOneResult)
// 插入多个值
misty := Trainer{"Misty", 10, "Cerulean City"}
brock := Trainer{"Brock", 15, "Pewter City"}
trainers := []interface{}{misty, brock}
insertManyResult := models.NewMgo().InsertMany(trainers)
fmt.Println("Inserted multiple documents: ", insertManyResult)
// 更新
update := bson.D{
{"$inc", bson.D{
{"age", 999},
}},
}
updateResult := models.NewMgo().UpdateOne("name", "Ash", update)
fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)
// 查询一个
var result Trainer
models.NewMgo().FindOne("name", "Ash").Decode(&result)
fmt.Printf("Found a single document: %+v\n", result)
// 查询总数
name, size := models.NewMgo().Count()
fmt.Printf(" documents name: %+v documents size %d \n", name, size)
// 查询多个记录
var results []*Trainer
cur := models.NewMgo().FindAll(0, size, 1)
defer cur.Close(context.TODO())
if cur != nil {
fmt.Println("FindAll err:", cur)
}
for cur.Next(context.TODO()) {
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)
}
// 遍历结果
for k, v := range results {
fmt.Printf("Found documents %d %v \n", k, v)
}
// 删除文件
deleteResult := models.NewMgo().DeleteMany("name", "Ash")
fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult)
// 关闭连接
// drivers.Close()
}
output
https://github.com/jinchunguang/go-mongo