-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdelete.go
More file actions
55 lines (47 loc) · 1.56 KB
/
delete.go
File metadata and controls
55 lines (47 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package mongo
import (
"context"
"time"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
)
// DeleteById 按id删除单条文档,并返回 driver 的 DeleteResult。
func Delete(ctx context.Context, collection *mongo.Collection, id string) (*mongo.DeleteResult, error) {
return collection.DeleteOne(ctx, bson.D{
{Key: "_id", Value: id},
})
}
// DeleteManyByIds 按id列表批量删除文档,并返回 driver 的 DeleteResult。
func DeleteManyByIds(ctx context.Context, collection *mongo.Collection, ids []string) (*mongo.DeleteResult, error) {
return collection.DeleteMany(ctx, bson.D{
{Key: "_id", Value: bson.D{
{Key: "$in", Value: ids},
}},
})
}
// SoftDeleteById 软删除单条文档:写入 updated_at 与 deleted_at,并返回 UpdateResult。
func SoftDeleteById(ctx context.Context, collection *mongo.Collection, id string) (*mongo.UpdateResult, error) {
timer := time.Now().UTC()
return collection.UpdateOne(ctx, bson.D{
{Key: "_id", Value: id},
}, bson.D{
{Key: "$set", Value: bson.M{
"updated_at": timer,
"deleted_at": timer,
}},
})
}
// SoftDeleteManyByIds 软删除多条文档:批量写入 updated_at 与 deleted_at,并返回 UpdateResult。
func SoftDeleteManyByIds(ctx context.Context, collection *mongo.Collection, ids []string) (*mongo.UpdateResult, error) {
timer := time.Now().UTC()
return collection.UpdateMany(ctx, bson.D{
{Key: "_id", Value: bson.D{
{Key: "$in", Value: ids},
}},
}, bson.D{
{Key: "$set", Value: bson.M{
"updated_at": timer,
"deleted_at": timer,
}},
})
}