From b0212ac3dd10bf2a4894f26bf8625ce05e6b8a71 Mon Sep 17 00:00:00 2001 From: KynixInHK Date: Wed, 31 Jul 2024 10:05:47 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86am=5Fmongo=E7=9A=84?= =?UTF-8?q?=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + am_docs/mongo.md | 65 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 am_docs/mongo.md diff --git a/README.md b/README.md index 774baac..03e9fe4 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ - Redis 配置和操作工具 - RSA 非对称加解密工具 - SMTP 邮件发送工具 +- MongoDB 配置和操作工具 ## 作者 Axiomatrix Org. diff --git a/am_docs/mongo.md b/am_docs/mongo.md new file mode 100644 index 0000000..e92e82f --- /dev/null +++ b/am_docs/mongo.md @@ -0,0 +1,65 @@ +# MongoDB 操作工具包 +用于操作MongoDB,简化开发流程。要使用此工具包,你的MongoDB**必须已经开启访问控制**。 + +## 使用方法 +### 连接数据库 + +```go +var mongodb = am_mongo.MongoDB{ + Host: "127.0..0.1", + Port: "27017", + Username: "root", + Password: "1234567" +} + +err := mongodb.Connect("testdb") + +defer am_mongo.Close() +``` + +### 创建Model和唯一索引 +```go +type User struct { + Name string `bson:"name"` + Age int `bson:"age"` + Email string `bson:"email"` +} + +mongodb.CreateUniqueIndex("testCollection", "email") +``` + +### CRUD +#### 插入 +```go +var user = User{ + Name: "Joe Biden", + Age: 82, + Email: "heyjoebiden@gmail.com" +} +err := mongodb.Insert("testCollection", &user) +``` + +#### 查询 +```go +// 条件查询 +var filter = bson.M{"email": "heyjowbiden@gmail.com"} +var results []User + +err := mongodb.Find("testCollection", filter, &results) + +// 全数查询 +err = mongodb.Find("testCollection", bson.M{}, &results) +``` + +#### 修改 +```go +var filter = bson.M{"email": "heyjowbiden@gmail.com"} +var update = bson.M{"name": "Donald J Trump"} +err := mongodb.Update("testCollection", filter, update) +``` + +#### 删除 +```go +var filter = bson.M{"email": "heyjowbiden@gmail.com"} +err := mongodb.Delete(filter) +``` \ No newline at end of file