package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Student struct {
Name string
Age int
}
func main() {
clientOptions := options.Client().ApplyURI("mongodb://192.168.236.139:27017")
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
collection := client.Database("articledb").Collection("houtai")
fmt.Println(collection)
collection = client.Database("school").Collection("student")
s1 := Student{"小黑", 13}
insertResult,err := collection.InsertOne(context.TODO(),s1)
if err != nil {
log.Fatal(err)
}
fmt.Println("插入成功: ", insertResult.InsertedID)
filter := bson.D{{"name", "小黑"}}
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 更新 %v 文档.\n", updateResult.MatchedCount, updateResult.ModifiedCount)
var result Student
err = collection.FindOne(context.TODO(),filter).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("查到文档: %+v\n", result)
findOptions := options.Find()
findOptions.SetLimit(10)
var results []*Student
cur, err := collection.Find(context.TODO(), bson.D{{"name", "小红"}}, findOptions)
if err != nil {
log.Fatal(err)
}
for cur.Next(context.TODO()) {
var elem Student
err := cur.Decode(&elem)
if err != nil {
log.Fatal(err)
}
results = append(results, &elem)
}
if err := cur.Err(); err != nil {
log.Fatal(err)
}
cur.Close(context.TODO())
fmt.Printf("Found multiple documents (array of pointers)=: %#v\n", results)
for _,val := range results{
fmt.Printf("%v\n",*val)
}
deleteResult1, err := collection.DeleteOne(context.TODO(), bson.D{{"name","小红"}})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Deleted %v documents in the trainers collection\n", deleteResult1.DeletedCount)
err = client.Disconnect(context.TODO())
if err != nil {
log.Fatal(err)
}
fmt.Println("断开连接成功")
}