🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 1.安装mongo-driver ~~~ go get go.mongodb.org/mongo-driver ~~~ ## 2.连接mongodb ~~~ func main() { clientOptions := options.Client().ApplyURI("mongodb://localhost: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!") } ~~~ ## 3.关闭连接 ~~~ err = client.Disconnect(context.TODO()) if err != nil { log.Fatal(err) } fmt.Println("Connection to MongoDB closed.") ~~~ ## 4.插入文档 ~~~ // 插入一条 func InsertOne(u User) { insertResult, err := collection.InsertOne(context.TODO(), u) if err != nil { log.Fatal(err) } fmt.Println("Inserted a single document: ", insertResult.InsertedID) } ~~~ ~~~ // 插入多条 func InsertMany(userList []interface{}) { insertManyResult, err := collection.InsertMany(context.TODO(), userList) if err != nil { log.Fatal(err) } fmt.Println("Inserted many documents: ",insertManyResult.InsertedIDs) } ~~~ ## 5.更新文档 ~~~ func UpdateOne() { filter := bson.D{{"name", "Alice"}} update := bson.D{ {"$inc", bson.D{ {"age", 101}, }}, } 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) } ~~~ ## 6.查找文档 ~~~ // 查找单个 func FindOne() { var user User filter := bson.D{{"name", "Alice"}} err := collection.FindOne(context.TODO(), filter).Decode(&user) if err != nil { log.Fatal(err) } fmt.Printf("Found a single document: %+v\n", user) } // 查找多个 ``` func FindMany() { findOptions := options.Find() findOptions.SetLimit(2) var user []*User cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions) if err != nil { log.Fatal(err) } for cur.Next(context.TODO()) { var u User err := cur.Decode(&u) if err != nil { log.Fatal(err) } user = append(user, &u) } if err := cur.Err(); err != nil { log.Fatal(err) } cur.Close(context.TODO()) fmt.Printf("Found multiple documents (array of pointers): %+v\n", user) for _, v := range user { fmt.Println(*v) } } ~~~ ## 7.删除文档 `collection.DeleteOne()` `collection.DeleteMany()` 删除单个、多个 `Collection.Drop()` 删除整个集合 **demo** ~~~ func main() { uri := "mongodb://localhost:27017" client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err := client.Disconnect(context.TODO()); err != nil { panic(err) } }() coll := client.Database("test").Collection("user") name := "Alice" var result bson.M err = coll.FindOne(context.TODO(), bson.D{{"name", name}}).Decode(&result) if err == mongo.ErrNoDocuments { fmt.Printf("No document was found with the title %s\n", name) return } if err != nil { panic(err) } jsonData, err := json.MarshalIndent(result, "", " ") if err != nil { panic(err) } fmt.Printf("%s\n", jsonData) } ~~~