一、MongoDB簡介
MongoDB是一個廣為流行的NoSQL數據庫,使用JSON格式進行數據存儲。與傳統關係型數據庫不同,MongoDB沒有固定的表結構,而是可以存儲各種類型的數據,支持動態的擴展。
MongoDB有多個版本,包括社區版和企業版等,其中最常用的是社區版,可以免費使用。
二、Go語言操作MongoDB的基本API
Go語言操作MongoDB可以使用mgo或官方提供的mongo-go-driver兩種庫,這裡介紹使用mongo-go-driver的基本API。
首先需要安裝mongo-go-driver庫:
go get go.mongodb.org/mongo-driver
接下來,首先需要建立與MongoDB的連接:
package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// Connect to MongoDB
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
log.Fatal(err)
}
// Ping the primary
err = client.Ping(ctx, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
}
上面的代碼連接了本地的MongoDB數據庫,並進行了Ping操作,確認是否連接成功。接下來可以進行數據庫的常規操作,比如插入、查詢、刪除等。
三、插入數據
插入數據可以使用Collection對象的InsertOne或InsertMany方法,使用bson庫構建文檔對象。示例如下:
package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Student struct {
Name string `bson:"name"`
Age int `bson:"age"`
Gender string `bson:"gender"`
Address string `bson:"address"`
}
func main() {
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// Connect to MongoDB
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
log.Fatal(err)
}
// Collection handle
collection := client.Database("test").Collection("student")
// Insert a single document
student := Student{"Tom", 18, "male", "Beijing"}
result, err := collection.InsertOne(ctx, student)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted student with ID:", result.InsertedID)
// Insert multiple documents
students := []interface{}{
Student{"Lucy", 17, "female", "Shanghai"},
Student{"Jerry", 19, "male", "Guangzhou"},
}
result, err = collection.InsertMany(ctx, students)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted documents with IDs:", result.InsertedIDs)
}
上面的代碼插入了兩個學生的數據,其中Student結構體的字段與MongoDB中的文檔字段通過bson標籤映射。InsertOne方法返回插入的文檔ID,InsertMany方法返回插入的多個文檔的ID。
四、查詢數據
查詢數據可以使用Collection對象的Find和FindOne方法,使用bson庫構建查詢條件。示例如下:
package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Student struct {
Name string `bson:"name"`
Age int `bson:"age"`
Gender string `bson:"gender"`
Address string `bson:"address"`
}
func main() {
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// Connect to MongoDB
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
log.Fatal(err)
}
// Collection handle
collection := client.Database("test").Collection("student")
// Find a single document
var result Student
err = collection.FindOne(ctx, bson.M{"name": "Tom"}).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Println("Found student with name:", result.Name)
// Find multiple documents
var results []Student
cur, err := collection.Find(ctx, bson.M{"age": bson.M{"$gt": 17}})
if err != nil {
log.Fatal(err)
}
defer cur.Close(ctx)
for cur.Next(ctx) {
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)
}
fmt.Printf("Found multiple students with age > 17: %+v\n", results)
}
上面的代碼查詢了一個名字為Tom的學生的數據,和年齡大於17歲的多個學生的數據。FindOne方法返回單個文檔,Find方法返回多個文檔的游標,需要使用Next方法迭代處理。
五、更新數據
更新數據可以使用Collection對象的UpdateOne或UpdateMany方法,使用bson庫構建查詢條件和更新文檔對象。示例如下:
package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Student struct {
Name string `bson:"name"`
Age int `bson:"age"`
Gender string `bson:"gender"`
Address string `bson:"address"`
}
func main() {
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// Connect to MongoDB
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
log.Fatal(err)
}
// Collection handle
collection := client.Database("test").Collection("student")
// Update a single document
filter := bson.M{"name": "Tom"}
update := bson.M{"$set": bson.M{"address": "Shenzhen"}}
result, err := collection.UpdateOne(ctx, filter, update)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Matched %v documents and updated %v documents.\n", result.MatchedCount, result.ModifiedCount)
// Update multiple documents
filter = bson.M{"age": bson.M{"$gt": 17}}
update = bson.M{"$set": bson.M{"gender": "unknown"}}
result, err = collection.UpdateMany(ctx, filter, update)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Matched %v documents and updated %v documents.\n", result.MatchedCount, result.ModifiedCount)
}
上面的代碼更新了一個名字為Tom的學生的地址數據,和年齡大於17歲的多個學生的性別數據。UpdateOne方法返回匹配和更新的文檔數量,UpdateMany方法也是如此。
六、刪除數據
刪除數據可以使用Collection對象的DeleteOne或DeleteMany方法,使用bson庫構建查詢條件。示例如下:
package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Student struct {
Name string `bson:"name"`
Age int `bson:"age"`
Gender string `bson:"gender"`
Address string `bson:"address"`
}
func main() {
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// Connect to MongoDB
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
log.Fatal(err)
}
// Collection handle
collection := client.Database("test").Collection("student")
// Delete a single document
filter := bson.M{"name": "Lucy"}
result, err := collection.DeleteOne(ctx, filter)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Deleted %v documents.\n", result.DeletedCount)
// Delete multiple documents
filter = bson.M{"age": bson.M{"$lt": 18}}
result, err = collection.DeleteMany(ctx, filter)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Deleted %v documents.\n", result.DeletedCount)
}
上面的代碼刪除了一個名字為Lucy的學生的數據,和年齡小於18歲的多個學生的數據。DeleteOne方法和UpdateOne方法類似,返回匹配和刪除的文檔數量,DeleteMany方法也是如此。
七、MongoDB常用操作符
MongoDB支持很多常用的操作符,比如:
- $eq: 等於
- $ne: 不等於
- $in: 在指定列表中
- $gt: 大於
- $lt: 小於
- $gte: 大於等於
- $lte: 小於等於
- $or: 或
- $and: 與
例如,查詢年齡在18到20歲之間的學生,可以使用以下代碼:
filter := bson.M{"age": bson.M{"$gte": 18, "$lte": 20}}
cur, err := collection.Find(ctx, filter)
八、總結
本文介紹了Go語言操作MongoDB的基本API,包括建立連接、插入數據、查詢數據、更新數據和刪除數據等。MongoDB具有高可擴展性和靈活性,適用於存儲大規模和非結構化的數據,對於複雜查詢、高並發和高容錯性的應用有很好的支持。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/301425.html