最近的微服务用到了mongodb
,所以先了解go
对于mongo
的CRUD
查找
import "go.mongodb.org/mongo-driver/mongo"
func (this *User) FindOneById(user_id int64) (*User, error) {
err := this.db.FindOne(nil, bson.D{{"id", user_id}}).Decode(this)
return this, err
}
func (this *User) FindOneByNameOrPhone(name string, phone string) (*User, error) {
conditions := bson.M{
"$or": []bson.M{
bson.M{"name": bson.M{"$eq": name}},
bson.M{"phone": bson.M{"$eq": phone}},
},
}
err := this.db.FindOne(context.TODO(), conditions).Decode(this)
return this, err
}
插入
type User struct {
Id int64 `bson:"id"`
Name string `bson:"name"`
NickName string `bson:"nickname"`
Password string `bson:"password"`
Phone string `bson:"phone"`
Email string `bson:"email"`
CreateTime int64 `bson:"create_time"`
UpdateTime int64 `bson:"update_time"`
db *mongo.Collection
}
func (this *User) Insert() (*mongo.InsertOneResult, error) {
return this.db.InsertOne(context.TODO(), this)
}
func (this *ActiveCode) InsertMany(acs []interface{}) (*mongo.InsertManyResult, error) {
return this.db.InsertMany(context.Background(), acs)
}
codes := []string{"a","b","c"}
acModel := model.NewActiveCode()
var data []interface{}
for _, i := range codes {
if i == "" {
continue
}
data = append(data,bson.D{
{"user_id", 0},
{"code", i},
{"status", 0},
{"data", ""},
{"create_time", time.Now().Unix()},
{"update_time", time.Now().Unix()},
})
}
result, err := acModel.InsertMany(data)
更新
func (this *User) UpdateById(userId int64, phone, email,nickName string) (interface{}, error) {
filter := bson.D{{"id", userId}}
update := bson.D{
{
"$set", bson.D{{"phone", phone}},
},
{
"$set", bson.D{{"email", email}},
},
{
"$set", bson.D{{"nickname", nickName}},
},
}
result, err := this.db.UpdateOne(context.TODO(), filter, update)
if err != nil {
return nil, err
}
return result.UpsertedID, nil
}
删除
func (this *User) deleteById(userId int64) error {
filter := bson.D{{"id", userId}}
_, err := this.db.DeleteOne(context.TODO(), filter)
if err != nil {
return err
}
return nil
}