您好,登錄后才能下訂單哦!
nohup ./bin/mongod --dbpath=./data &
package main
//導(dǎo)入
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"os"
"time"
)
type Howie struct {
//struct里面獲取ObjectID
HowieId primitive.ObjectID `bson:"_id"`
Name string
Pwd string
Age int64
CreateTime int64
}
func main() {
TestMongo("mongodb://0.0.0.0:27017")
}
func TestMongo(url string) {
var (
err error
client *mongo.Client
collection *mongo.Collection
insertOneRes *mongo.InsertOneResult
insertManyRes *mongo.InsertManyResult
delRes *mongo.DeleteResult
updateRes *mongo.UpdateResult
cursor *mongo.Cursor
howieArray = GetHowieArray()
howie Howie
howieArrayEmpty []Howie
size int64
)
//鏈接mongo服務(wù)
if client, err = mongo.Connect(getContext(), options.Client().ApplyURI(url)); err != nil {
checkErr(err)
}
//判斷服務(wù)是否可用
if err = client.Ping(getContext(), readpref.Primary()); err != nil {
checkErr(err)
}
//選擇數(shù)據(jù)庫和集合
collection = client.Database("testing_base").Collection("howie")
//刪除這個集合
collection.Drop(getContext())
//插入一條數(shù)據(jù)
if insertOneRes, err = collection.InsertOne(getContext(), howieArray[0]); err != nil {
checkErr(err)
}
fmt.Printf("InsertOne插入的消息ID:%v\n", insertOneRes.InsertedID)
//批量插入數(shù)據(jù)
if insertManyRes, err = collection.InsertMany(getContext(), howieArray[1:]); err != nil {
checkErr(err)
}
fmt.Printf("InsertMany插入的消息ID:%v\n", insertManyRes.InsertedIDs)
var Dinfo = make(map[string]interface{})
err = collection.FindOne(getContext(), bson.D{{"name", "howie_2"}, {"age", 11}}).Decode(&Dinfo)
fmt.Println(Dinfo)
fmt.Println("_id", Dinfo["_id"])
//查詢單條數(shù)據(jù)
if err = collection.FindOne(getContext(), bson.D{{"name", "howie_2"}, {"age", 11}}).Decode(&howie); err != nil {
checkErr(err)
}
fmt.Printf("FindOne查詢到的數(shù)據(jù):%v\n", howie)
//查詢單條數(shù)據(jù)后刪除該數(shù)據(jù)
if err = collection.FindOneAndDelete(getContext(), bson.D{{"name", "howie_3"}}).Decode(&howie); err != nil {
checkErr(err)
}
fmt.Printf("FindOneAndDelete查詢到的數(shù)據(jù):%v\n", howie)
//查詢單條數(shù)據(jù)后修改該數(shù)據(jù)
if err = collection.FindOneAndUpdate(getContext(), bson.D{{"name", "howie_4"}}, bson.M{"$set": bson.M{"name": "這條數(shù)據(jù)我需要修改了"}}).Decode(&howie); err != nil {
checkErr(err)
}
fmt.Printf("FindOneAndUpdate查詢到的數(shù)據(jù):%v\n", howie)
//查詢單條數(shù)據(jù)后替換該數(shù)據(jù)(以前的數(shù)據(jù)全部清空)
if err = collection.FindOneAndReplace(getContext(), bson.D{{"name", "howie_5"}}, bson.M{"hero": "這條數(shù)據(jù)我替換了"}).Decode(&howie); err != nil {
checkErr(err)
}
fmt.Printf("FindOneAndReplace查詢到的數(shù)據(jù):%v\n", howie)
//一次查詢多條數(shù)據(jù)
// 查詢createtime>=3
// 限制取2條
// createtime從大到小排序的數(shù)據(jù)
if cursor, err = collection.Find(getContext(), bson.M{"createtime": bson.M{"$gte": 2}}, options.Find().SetLimit(2), options.Find().SetSort(bson.M{"createtime": -1})); err != nil {
checkErr(err)
}
if err = cursor.Err(); err != nil {
checkErr(err)
}
defer cursor.Close(context.Background())
for cursor.Next(context.Background()) {
if err = cursor.Decode(&howie); err != nil {
checkErr(err)
}
howieArrayEmpty = append(howieArrayEmpty, howie)
}
for _, v := range howieArrayEmpty {
fmt.Printf("Find查詢到的數(shù)據(jù)ObejectId值%s 值:%v\n", v.HowieId.Hex(), v)
}
//查詢集合里面有多少數(shù)據(jù)
if size, err = collection.CountDocuments(getContext(),bson.D{}); err != nil {
checkErr(err)
}
fmt.Printf("Count里面有多少條數(shù)據(jù):%d\n", size)
//查詢集合里面有多少數(shù)據(jù)(查詢createtime>=3的數(shù)據(jù))
if size, err = collection.CountDocuments(getContext(), bson.M{"createtime": bson.M{"$gte": 3}}); err != nil {
checkErr(err)
}
fmt.Printf("Count里面有多少條數(shù)據(jù):%d\n", size)
//修改一條數(shù)據(jù)
if updateRes, err = collection.UpdateOne(getContext(), bson.M{"name": "howie_2"}, bson.M{"$set": bson.M{"name": "我要改了他的名字"}}); err != nil {
checkErr(err)
}
fmt.Printf("UpdateOne的數(shù)據(jù):%d\n", updateRes)
//修改多條數(shù)據(jù)
if updateRes, err = collection.UpdateMany(getContext(), bson.M{"createtime": bson.M{"$gte": 3}}, bson.M{"$set": bson.M{"name": "我要批量改了他的名字"}}); err != nil {
checkErr(err)
}
fmt.Printf("UpdateMany的數(shù)據(jù):%d\n", updateRes)
//刪除一條數(shù)據(jù)
if delRes, err = collection.DeleteOne(getContext(), bson.M{"name": "howie_1"}); err != nil {
checkErr(err)
}
fmt.Printf("DeleteOne刪除了多少條數(shù)據(jù):%d\n", delRes.DeletedCount)
//刪除多條數(shù)據(jù)
if delRes, err = collection.DeleteMany(getContext(), bson.M{"createtime": bson.M{"$gte": 7}}); err != nil {
checkErr(err)
}
fmt.Printf("DeleteMany刪除了多少條數(shù)據(jù):%d\n", delRes.DeletedCount)
}
func checkErr(err error) {
if err != nil {
if err == mongo.ErrNoDocuments {
fmt.Println("沒有查到數(shù)據(jù)")
os.Exit(0)
} else {
fmt.Println(err)
os.Exit(0)
}
}
}
func getContext() (ctx context.Context) {
ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)
return
}
func GetHowieArray() (data []interface{}) {
var i int64
for i = 0; i <= 10; i++ {
data = append(data, Howie{
HowieId: primitive.NewObjectID(),
Name: fmt.Sprintf("howie_%d", i+1),
Pwd: fmt.Sprintf("pwd_%d", i+1),
Age: i + 10,
CreateTime: i + 1,
})
}
return
}
注意:從github.com/mongodb/mongo-go-driver下載下來要放到go.mongodb.org目錄對應(yīng)的位置,不然會報錯
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。