删除未使用的RandomSoftDelete方法并修复limit条件逻辑

This commit is contained in:
2026-01-22 19:07:10 +08:00
committed by 张斌
parent 88d9d2b8a6
commit 731a2a479d

View File

@@ -197,7 +197,6 @@ func (m *MongoDB) Find(ctx context.Context, filter bson.M, result interface{}, c
opt := options.Find().SetSkip(skip)
if limit != -1 {
opt.SetLimit(limit)
} else {
total, err = m.Count(ctx, filter, collection)
if err != nil || total == 0 {
return
@@ -521,53 +520,6 @@ func (m *MongoDB) Update(ctx context.Context, filter bson.M, update bson.M, coll
return
}
// RandomSoftDelete 随机软删除个文档的 _id
func (m *MongoDB) RandomSoftDelete(ctx context.Context, limit int, collection string, opts ...options.Lister[options.UpdateManyOptions]) (result *mongo.UpdateResult, err error) {
source, err := m.getDataSource()
if err != nil {
return nil, err
}
db := source.Database()
_ = opts
pipeline := mongo.Pipeline{
bson.D{{Key: "$addFields", Value: bson.D{{Key: "random", Value: bson.M{"$rand": bson.M{}}}}}},
bson.D{{Key: "$match", Value: bson.D{{Key: "isDeleted", Value: false}}}},
bson.D{{Key: "$sort", Value: bson.D{{Key: "random", Value: -1}}}},
bson.D{{Key: "$limit", Value: limit}},
bson.D{{Key: "$project", Value: bson.D{{Key: "_id", Value: 1}}}},
}
cursor, err := db.Collection(collection).Aggregate(ctx, pipeline)
if err != nil {
return
}
defer cursor.Close(ctx)
var idsToUpdate []bson.ObjectID
for cursor.Next(ctx) {
var result bson.M
if err := cursor.Decode(&result); err != nil {
return nil, err
}
id := result["_id"].(bson.ObjectID)
idsToUpdate = append(idsToUpdate, id)
}
if err := cursor.Err(); err != nil {
return nil, err
}
fmt.Printf("准备更新的随机文档ID: %v\n", idsToUpdate)
if len(idsToUpdate) > 0 {
filter := bson.D{{Key: "_id", Value: bson.D{{Key: "$in", Value: idsToUpdate}}}}
update := bson.D{{Key: "$set", Value: bson.D{{Key: "isDeleted", Value: true}}}}
_, err = db.Collection(collection).UpdateMany(ctx, filter, update)
if err != nil {
return
}
}
return
}
// SaveOrUpdate 批量增加或修改
func (m *MongoDB) SaveOrUpdate(ctx context.Context, filter []bson.M, update []bson.M, collection string, opts ...options.Lister[options.UpdateManyOptions]) (result *mongo.BulkWriteResult, err error) {
source, err := m.getDataSource()