mongodb 取字段最大值
由于表使用了redis
自增的ID
, 如果redis
的数据误删,导致自增ID
会重复,所以这里会增加判断,如果相等,则获取最大ID
// mongo shell
db.user.aggregate([{"$group":{"_id":"", "max":{"$max":"$id"}}}])
// 结果
{
"_id" : "",
"max" : NumberLong(4)
}
// 同样可以
db.user.find().sort({id:-1}).skip(0).limit(1);
// 自增ID
func (this *Slideshow) GetId() (id int64, err error) {
key := "model_table_id"
b, err := svc.ServiceContextObj.RedisClient.Exists(key)
if err != nil {
return 0, err
}
if b == false { //不存在设为1,并返回
svc.ServiceContextObj.RedisClient.Set(key, "1")
return 1, nil
}
incr, err := svc.ServiceContextObj.RedisClient.Incr(key)
// 查询表
table, _ := this.FindOneById(incr)
// 如果存在,则获取最大ID + 1, 解决自增冲突
if table.Id == incr {
incr = this.FindMaxId() + 1
}
return incr, err
}
// 根据id查找
func (this *Slideshow) FindOneById(id int64) (*Slideshow, error) {
filter := bson.D{{"id", id}}
err := this.db.FindOne(context.TODO(), filter).Decode(this)
return this, err
}
// 查找最大ID
func (this *Slideshow) FindMaxId() int64 {
filter := []bson.M{
{
"$group": bson.M{
"_id": "",
"max": bson.M{"$max": "$id"},
},
},
}
var result []bson.M
cur, err := this.db.Aggregate(context.TODO(), filter)
if err != nil {
logx.Error(err)
}
_ = cur.All(context.TODO(), &result)
return result[0]["max"].(int64)
}
本作品采用《CC 协议》,转载必须注明作者和本文链接