optimized_go_tools/am_docs/mongo.md

65 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 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)
```