|
|
@@ -0,0 +1,591 @@
|
|
|
1
|
+package mongodb
|
|
|
2
|
+
|
|
|
3
|
+import (
|
|
|
4
|
+ "context"
|
|
|
5
|
+ "crypto/tls"
|
|
|
6
|
+ "fmt"
|
|
|
7
|
+ "log"
|
|
|
8
|
+ "sync"
|
|
|
9
|
+ "time"
|
|
|
10
|
+
|
|
|
11
|
+ "git.x2erp.com/qdy/go-base/config/subconfigs"
|
|
|
12
|
+ "git.x2erp.com/qdy/go-base/logger"
|
|
|
13
|
+ "go.mongodb.org/mongo-driver/bson"
|
|
|
14
|
+ "go.mongodb.org/mongo-driver/mongo"
|
|
|
15
|
+ "go.mongodb.org/mongo-driver/mongo/options"
|
|
|
16
|
+ "go.mongodb.org/mongo-driver/mongo/readpref"
|
|
|
17
|
+)
|
|
|
18
|
+
|
|
|
19
|
+// MongoDBFactory MongoDB工厂(全局单例模式)
|
|
|
20
|
+type MongoDBFactory struct {
|
|
|
21
|
+ client *mongo.Client
|
|
|
22
|
+ db *mongo.Database
|
|
|
23
|
+ config *subconfigs.MongoDBConfig
|
|
|
24
|
+ //mu sync.RWMutex // 添加读写锁保护
|
|
|
25
|
+}
|
|
|
26
|
+
|
|
|
27
|
+var (
|
|
|
28
|
+ instanceMongodb *MongoDBFactory
|
|
|
29
|
+ instanceMongodbOnce sync.Once
|
|
|
30
|
+ initErr error
|
|
|
31
|
+)
|
|
|
32
|
+
|
|
|
33
|
+// GetMongoDBFactory 获取MongoDB工厂单例
|
|
|
34
|
+func GetMongoDBFactory(config *subconfigs.MongoDBConfig) *MongoDBFactory {
|
|
|
35
|
+
|
|
|
36
|
+ instanceMongodbOnce.Do(func() {
|
|
|
37
|
+ if config == nil {
|
|
|
38
|
+ log.Fatal("配置未初始化,请先在yaml进行配置")
|
|
|
39
|
+ }
|
|
|
40
|
+
|
|
|
41
|
+ // 设置默认值
|
|
|
42
|
+ if config.Timeout == 0 {
|
|
|
43
|
+ config.Timeout = 20 * time.Second
|
|
|
44
|
+ }
|
|
|
45
|
+ if config.MaxPoolSize == 0 {
|
|
|
46
|
+ config.MaxPoolSize = 100
|
|
|
47
|
+ }
|
|
|
48
|
+ if config.MinPoolSize == 0 {
|
|
|
49
|
+ config.MinPoolSize = 10
|
|
|
50
|
+ }
|
|
|
51
|
+ if config.AuthSource == "" {
|
|
|
52
|
+ config.AuthSource = "admin"
|
|
|
53
|
+ }
|
|
|
54
|
+
|
|
|
55
|
+ // 验证配置
|
|
|
56
|
+ if config.URI == "" {
|
|
|
57
|
+ initErr = fmt.Errorf("mongodb URI must be configured")
|
|
|
58
|
+ return
|
|
|
59
|
+ }
|
|
|
60
|
+ if config.Database == "" {
|
|
|
61
|
+ initErr = fmt.Errorf("mongodb database name must be configured")
|
|
|
62
|
+ return
|
|
|
63
|
+ }
|
|
|
64
|
+
|
|
|
65
|
+ log.Printf("Creating MongoDB connection...")
|
|
|
66
|
+
|
|
|
67
|
+ // 创建客户端选项
|
|
|
68
|
+ clientOptions := options.Client().
|
|
|
69
|
+ ApplyURI(config.URI).
|
|
|
70
|
+ SetConnectTimeout(config.Timeout).
|
|
|
71
|
+ SetSocketTimeout(config.Timeout).
|
|
|
72
|
+ SetServerSelectionTimeout(config.Timeout).
|
|
|
73
|
+ SetMaxPoolSize(config.MaxPoolSize).
|
|
|
74
|
+ SetMinPoolSize(config.MinPoolSize).
|
|
|
75
|
+ SetMaxConnIdleTime(5 * time.Minute).
|
|
|
76
|
+ SetHeartbeatInterval(10 * time.Second)
|
|
|
77
|
+
|
|
|
78
|
+ // 设置认证
|
|
|
79
|
+ if config.Username != "" && config.Password != "" {
|
|
|
80
|
+ clientOptions.SetAuth(options.Credential{
|
|
|
81
|
+ Username: config.Username,
|
|
|
82
|
+ Password: config.Password,
|
|
|
83
|
+ AuthSource: config.AuthSource,
|
|
|
84
|
+ })
|
|
|
85
|
+ }
|
|
|
86
|
+
|
|
|
87
|
+ // 设置SSL
|
|
|
88
|
+ if config.SSL {
|
|
|
89
|
+ clientOptions.SetTLSConfig(&tls.Config{
|
|
|
90
|
+ InsecureSkipVerify: false,
|
|
|
91
|
+ })
|
|
|
92
|
+ }
|
|
|
93
|
+
|
|
|
94
|
+ // 创建上下文
|
|
|
95
|
+ ctx, cancel := context.WithTimeout(context.Background(), config.Timeout)
|
|
|
96
|
+ defer cancel()
|
|
|
97
|
+
|
|
|
98
|
+ log.Printf(" context.WithTimeout ... successfully.")
|
|
|
99
|
+
|
|
|
100
|
+ // 连接MongoDB
|
|
|
101
|
+ client, err := mongo.Connect(ctx, clientOptions)
|
|
|
102
|
+ if err != nil {
|
|
|
103
|
+ initErr = fmt.Errorf("failed to connect to MongoDB: %v", err)
|
|
|
104
|
+ return
|
|
|
105
|
+ }
|
|
|
106
|
+
|
|
|
107
|
+ log.Printf(" mongo.connect ... successfully.")
|
|
|
108
|
+
|
|
|
109
|
+ // // 测试连接
|
|
|
110
|
+ // if err := client.Ping(ctx, nil); err != nil {
|
|
|
111
|
+ // initErr = fmt.Errorf("failed to ping MongoDB: %v", err)
|
|
|
112
|
+ // return
|
|
|
113
|
+ // }
|
|
|
114
|
+
|
|
|
115
|
+ // 获取数据库
|
|
|
116
|
+ database := client.Database(config.Database)
|
|
|
117
|
+
|
|
|
118
|
+ log.Printf("MongoDBFactory is successfully created.\n")
|
|
|
119
|
+
|
|
|
120
|
+ instanceMongodb = &MongoDBFactory{
|
|
|
121
|
+ client: client,
|
|
|
122
|
+ db: database,
|
|
|
123
|
+ config: config,
|
|
|
124
|
+ }
|
|
|
125
|
+ })
|
|
|
126
|
+
|
|
|
127
|
+ if initErr != nil {
|
|
|
128
|
+ //logger.Errorf("MongoDBFactory is error:'%v'", initErr)
|
|
|
129
|
+ log.Fatalf("MongoDBFactory is error:'%v'", initErr)
|
|
|
130
|
+ //return nil
|
|
|
131
|
+ }
|
|
|
132
|
+
|
|
|
133
|
+ return instanceMongodb
|
|
|
134
|
+}
|
|
|
135
|
+
|
|
|
136
|
+// ========== MongoDBFactory 实例方法 ==========
|
|
|
137
|
+
|
|
|
138
|
+// GetClient 获取MongoDB客户端
|
|
|
139
|
+func (f *MongoDBFactory) GetClient() *mongo.Client {
|
|
|
140
|
+ return f.client
|
|
|
141
|
+}
|
|
|
142
|
+
|
|
|
143
|
+// GetDatabase 获取数据库
|
|
|
144
|
+func (f *MongoDBFactory) GetDatabase() *mongo.Database {
|
|
|
145
|
+ return f.db
|
|
|
146
|
+}
|
|
|
147
|
+
|
|
|
148
|
+// GetCollection 获取集合(类似获取数据库连接)
|
|
|
149
|
+func (f *MongoDBFactory) GetCollection(collectionName string) *mongo.Collection {
|
|
|
150
|
+ return f.db.Collection(collectionName)
|
|
|
151
|
+}
|
|
|
152
|
+
|
|
|
153
|
+// Close 关闭MongoDB连接
|
|
|
154
|
+func (f *MongoDBFactory) Close() {
|
|
|
155
|
+ if f.client != nil {
|
|
|
156
|
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
|
157
|
+ defer cancel()
|
|
|
158
|
+
|
|
|
159
|
+ err := f.client.Disconnect(ctx)
|
|
|
160
|
+ if err != nil {
|
|
|
161
|
+ logger.Errorf("failed to disconnect MongoDB: %v", err)
|
|
|
162
|
+ //return fmt.Errorf("failed to disconnect MongoDB: %v", err)
|
|
|
163
|
+ }
|
|
|
164
|
+
|
|
|
165
|
+ log.Printf("MongoDB connection closed gracefully\n")
|
|
|
166
|
+ f.client = nil
|
|
|
167
|
+ f.db = nil
|
|
|
168
|
+ }
|
|
|
169
|
+
|
|
|
170
|
+}
|
|
|
171
|
+
|
|
|
172
|
+// GetConfig 获取配置信息
|
|
|
173
|
+func (f *MongoDBFactory) GetConfig() subconfigs.MongoDBConfig {
|
|
|
174
|
+ return *f.config
|
|
|
175
|
+}
|
|
|
176
|
+
|
|
|
177
|
+// TestConnection 测试连接
|
|
|
178
|
+func (f *MongoDBFactory) TestConnection() error {
|
|
|
179
|
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
180
|
+ defer cancel()
|
|
|
181
|
+
|
|
|
182
|
+ return f.client.Ping(ctx, readpref.Primary())
|
|
|
183
|
+}
|
|
|
184
|
+
|
|
|
185
|
+// ========== 快捷操作方法(增强版) ==========
|
|
|
186
|
+
|
|
|
187
|
+// InsertOne 插入单个文档,返回是否成功
|
|
|
188
|
+func (f *MongoDBFactory) InsertOne(collectionName string, document interface{}) bool {
|
|
|
189
|
+ collection := f.GetCollection(collectionName)
|
|
|
190
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
191
|
+ defer cancel()
|
|
|
192
|
+
|
|
|
193
|
+ _, err := collection.InsertOne(ctx, document)
|
|
|
194
|
+ if err != nil {
|
|
|
195
|
+ logger.Errorf("插入文档失败,集合:%s,错误:%v", collectionName, err)
|
|
|
196
|
+ return false
|
|
|
197
|
+ }
|
|
|
198
|
+ return true
|
|
|
199
|
+}
|
|
|
200
|
+
|
|
|
201
|
+// InsertOneWithResult 插入单个文档并返回结果
|
|
|
202
|
+func (f *MongoDBFactory) InsertOneWithResult(collectionName string, document interface{}) (*mongo.InsertOneResult, bool) {
|
|
|
203
|
+ collection := f.GetCollection(collectionName)
|
|
|
204
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
205
|
+ defer cancel()
|
|
|
206
|
+
|
|
|
207
|
+ result, err := collection.InsertOne(ctx, document)
|
|
|
208
|
+ if err != nil {
|
|
|
209
|
+ logger.Errorf("插入文档失败,集合:%s,错误:%v", collectionName, err)
|
|
|
210
|
+ return nil, false
|
|
|
211
|
+ }
|
|
|
212
|
+ return result, true
|
|
|
213
|
+}
|
|
|
214
|
+
|
|
|
215
|
+// InsertMany 插入多个文档,返回是否成功
|
|
|
216
|
+func (f *MongoDBFactory) InsertMany(collectionName string, documents []interface{}) bool {
|
|
|
217
|
+ collection := f.GetCollection(collectionName)
|
|
|
218
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
219
|
+ defer cancel()
|
|
|
220
|
+
|
|
|
221
|
+ _, err := collection.InsertMany(ctx, documents)
|
|
|
222
|
+ if err != nil {
|
|
|
223
|
+ logger.Errorf("批量插入文档失败,集合:%s,错误:%v", collectionName, err)
|
|
|
224
|
+ return false
|
|
|
225
|
+ }
|
|
|
226
|
+ return true
|
|
|
227
|
+}
|
|
|
228
|
+
|
|
|
229
|
+// InsertManyWithResult 插入多个文档并返回结果
|
|
|
230
|
+func (f *MongoDBFactory) InsertManyWithResult(collectionName string, documents []interface{}) (*mongo.InsertManyResult, bool) {
|
|
|
231
|
+ collection := f.GetCollection(collectionName)
|
|
|
232
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
233
|
+ defer cancel()
|
|
|
234
|
+
|
|
|
235
|
+ result, err := collection.InsertMany(ctx, documents)
|
|
|
236
|
+ if err != nil {
|
|
|
237
|
+ logger.Errorf("批量插入文档失败,集合:%s,错误:%v", collectionName, err)
|
|
|
238
|
+ return nil, false
|
|
|
239
|
+ }
|
|
|
240
|
+ return result, true
|
|
|
241
|
+}
|
|
|
242
|
+
|
|
|
243
|
+// FindOne 查询单个文档,返回解码后的对象
|
|
|
244
|
+func (f *MongoDBFactory) FindOne(collectionName string, filter interface{}, result interface{}) error {
|
|
|
245
|
+ collection := f.GetCollection(collectionName)
|
|
|
246
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
247
|
+ defer cancel()
|
|
|
248
|
+
|
|
|
249
|
+ err := collection.FindOne(ctx, filter).Decode(result)
|
|
|
250
|
+ if err != nil {
|
|
|
251
|
+ if err != mongo.ErrNoDocuments {
|
|
|
252
|
+ logger.Errorf("查询文档失败,集合:%s,过滤条件:%v,错误:%v", collectionName, filter, err)
|
|
|
253
|
+ }
|
|
|
254
|
+ return err
|
|
|
255
|
+ }
|
|
|
256
|
+ return nil
|
|
|
257
|
+}
|
|
|
258
|
+
|
|
|
259
|
+// FindOneAndDecode 查询单个文档并自动解码(简化版)
|
|
|
260
|
+func (f *MongoDBFactory) FindOneAndDecode(collectionName string, filter interface{}) (interface{}, error) {
|
|
|
261
|
+ collection := f.GetCollection(collectionName)
|
|
|
262
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
263
|
+ defer cancel()
|
|
|
264
|
+
|
|
|
265
|
+ var result map[string]interface{}
|
|
|
266
|
+ err := collection.FindOne(ctx, filter).Decode(&result)
|
|
|
267
|
+ if err != nil {
|
|
|
268
|
+ if err != mongo.ErrNoDocuments {
|
|
|
269
|
+ logger.Errorf("查询文档失败,集合:%s,过滤条件:%v,错误:%v", collectionName, filter, err)
|
|
|
270
|
+ }
|
|
|
271
|
+ return nil, err
|
|
|
272
|
+ }
|
|
|
273
|
+ return result, nil
|
|
|
274
|
+}
|
|
|
275
|
+
|
|
|
276
|
+// Find 查询多个文档,返回对象数组
|
|
|
277
|
+func (f *MongoDBFactory) Find(collectionName string, filter interface{}, results interface{}, opts ...*options.FindOptions) error {
|
|
|
278
|
+ collection := f.GetCollection(collectionName)
|
|
|
279
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
280
|
+ defer cancel()
|
|
|
281
|
+
|
|
|
282
|
+ cursor, err := collection.Find(ctx, filter, opts...)
|
|
|
283
|
+ if err != nil {
|
|
|
284
|
+ logger.Errorf("查询文档失败,集合:%s,过滤条件:%v,错误:%v", collectionName, filter, err)
|
|
|
285
|
+ return err
|
|
|
286
|
+ }
|
|
|
287
|
+ defer cursor.Close(ctx)
|
|
|
288
|
+
|
|
|
289
|
+ // 解码到传入的切片指针中
|
|
|
290
|
+ if err = cursor.All(ctx, results); err != nil {
|
|
|
291
|
+ logger.Errorf("解码查询结果失败,集合:%s,错误:%v", collectionName, err)
|
|
|
292
|
+ return err
|
|
|
293
|
+ }
|
|
|
294
|
+ return nil
|
|
|
295
|
+}
|
|
|
296
|
+
|
|
|
297
|
+// FindAll 查询所有文档,返回对象数组
|
|
|
298
|
+func (f *MongoDBFactory) FindAll(collectionName string, results interface{}) error {
|
|
|
299
|
+ return f.Find(collectionName, bson.M{}, results)
|
|
|
300
|
+}
|
|
|
301
|
+
|
|
|
302
|
+// UpdateOneWithResult 更新单个文档并返回结果
|
|
|
303
|
+func (f *MongoDBFactory) UpdateOneWithResult(collectionName string, filter interface{}, update interface{}) (*mongo.UpdateResult, bool) {
|
|
|
304
|
+ collection := f.GetCollection(collectionName)
|
|
|
305
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
306
|
+ defer cancel()
|
|
|
307
|
+
|
|
|
308
|
+ result, err := collection.UpdateOne(ctx, filter, update)
|
|
|
309
|
+ if err != nil {
|
|
|
310
|
+ logger.Errorf("更新文档失败,集合:%s,过滤条件:%v,错误:%v", collectionName, filter, err)
|
|
|
311
|
+ return nil, false
|
|
|
312
|
+ }
|
|
|
313
|
+ return result, true
|
|
|
314
|
+}
|
|
|
315
|
+
|
|
|
316
|
+// CountDocuments 统计文档数量,返回数量
|
|
|
317
|
+func (f *MongoDBFactory) CountDocuments(collectionName string, filter interface{}) (int64, error) {
|
|
|
318
|
+ collection := f.GetCollection(collectionName)
|
|
|
319
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
320
|
+ defer cancel()
|
|
|
321
|
+
|
|
|
322
|
+ count, err := collection.CountDocuments(ctx, filter)
|
|
|
323
|
+ if err != nil {
|
|
|
324
|
+ logger.Errorf("统计文档数量失败,集合:%s,过滤条件:%v,错误:%v", collectionName, filter, err)
|
|
|
325
|
+ return 0, err
|
|
|
326
|
+ }
|
|
|
327
|
+ return count, nil
|
|
|
328
|
+}
|
|
|
329
|
+
|
|
|
330
|
+// Aggregate 聚合查询,返回对象数组
|
|
|
331
|
+func (f *MongoDBFactory) Aggregate(collectionName string, pipeline interface{}, results interface{}) error {
|
|
|
332
|
+ collection := f.GetCollection(collectionName)
|
|
|
333
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
334
|
+ defer cancel()
|
|
|
335
|
+
|
|
|
336
|
+ cursor, err := collection.Aggregate(ctx, pipeline)
|
|
|
337
|
+ if err != nil {
|
|
|
338
|
+ logger.Errorf("聚合查询失败,集合:%s,管道:%v,错误:%v", collectionName, pipeline, err)
|
|
|
339
|
+ return err
|
|
|
340
|
+ }
|
|
|
341
|
+ defer cursor.Close(ctx)
|
|
|
342
|
+
|
|
|
343
|
+ if err = cursor.All(ctx, results); err != nil {
|
|
|
344
|
+ logger.Errorf("解码聚合结果失败,集合:%s,错误:%v", collectionName, err)
|
|
|
345
|
+ return err
|
|
|
346
|
+ }
|
|
|
347
|
+ return nil
|
|
|
348
|
+}
|
|
|
349
|
+
|
|
|
350
|
+// FindOneAndUpdate 查找并更新,返回更新后的文档
|
|
|
351
|
+func (f *MongoDBFactory) FindOneAndUpdate(collectionName string, filter interface{}, update interface{}, result interface{}) error {
|
|
|
352
|
+ collection := f.GetCollection(collectionName)
|
|
|
353
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
354
|
+ defer cancel()
|
|
|
355
|
+
|
|
|
356
|
+ err := collection.FindOneAndUpdate(ctx, filter, update).Decode(result)
|
|
|
357
|
+ if err != nil {
|
|
|
358
|
+ if err != mongo.ErrNoDocuments {
|
|
|
359
|
+ logger.Errorf("查找并更新失败,集合:%s,过滤条件:%v,错误:%v", collectionName, filter, err)
|
|
|
360
|
+ }
|
|
|
361
|
+ return err
|
|
|
362
|
+ }
|
|
|
363
|
+ return nil
|
|
|
364
|
+}
|
|
|
365
|
+
|
|
|
366
|
+// FindOneAndDelete 查找并删除,返回删除的文档
|
|
|
367
|
+func (f *MongoDBFactory) FindOneAndDelete(collectionName string, filter interface{}, result interface{}) error {
|
|
|
368
|
+ collection := f.GetCollection(collectionName)
|
|
|
369
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
370
|
+ defer cancel()
|
|
|
371
|
+
|
|
|
372
|
+ err := collection.FindOneAndDelete(ctx, filter).Decode(result)
|
|
|
373
|
+ if err != nil {
|
|
|
374
|
+ if err != mongo.ErrNoDocuments {
|
|
|
375
|
+ logger.Errorf("查找并删除失败,集合:%s,过滤条件:%v,错误:%v", collectionName, filter, err)
|
|
|
376
|
+ }
|
|
|
377
|
+ return err
|
|
|
378
|
+ }
|
|
|
379
|
+ return nil
|
|
|
380
|
+}
|
|
|
381
|
+
|
|
|
382
|
+// BulkWrite 批量写入操作,返回是否成功
|
|
|
383
|
+func (f *MongoDBFactory) BulkWrite(collectionName string, operations []mongo.WriteModel) bool {
|
|
|
384
|
+ collection := f.GetCollection(collectionName)
|
|
|
385
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
386
|
+ defer cancel()
|
|
|
387
|
+
|
|
|
388
|
+ _, err := collection.BulkWrite(ctx, operations)
|
|
|
389
|
+ if err != nil {
|
|
|
390
|
+ logger.Errorf("批量写入操作失败,集合:%s,错误:%v", collectionName, err)
|
|
|
391
|
+ return false
|
|
|
392
|
+ }
|
|
|
393
|
+ return true
|
|
|
394
|
+}
|
|
|
395
|
+
|
|
|
396
|
+// CreateIndex 创建索引,返回是否成功
|
|
|
397
|
+func (f *MongoDBFactory) CreateIndex(collectionName string, keys interface{}, opts ...*options.IndexOptions) bool {
|
|
|
398
|
+ collection := f.GetCollection(collectionName)
|
|
|
399
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
400
|
+ defer cancel()
|
|
|
401
|
+
|
|
|
402
|
+ indexModel := mongo.IndexModel{
|
|
|
403
|
+ Keys: keys,
|
|
|
404
|
+ }
|
|
|
405
|
+
|
|
|
406
|
+ if len(opts) > 0 && opts[0] != nil {
|
|
|
407
|
+ indexModel.Options = opts[0]
|
|
|
408
|
+ }
|
|
|
409
|
+
|
|
|
410
|
+ _, err := collection.Indexes().CreateOne(ctx, indexModel)
|
|
|
411
|
+ if err != nil {
|
|
|
412
|
+ logger.Errorf("创建索引失败,集合:%s,键:%v,错误:%v", collectionName, keys, err)
|
|
|
413
|
+ return false
|
|
|
414
|
+ }
|
|
|
415
|
+ return true
|
|
|
416
|
+}
|
|
|
417
|
+
|
|
|
418
|
+// FindWithPagination 分页查询,返回对象数组
|
|
|
419
|
+func (f *MongoDBFactory) FindWithPagination(
|
|
|
420
|
+ collectionName string,
|
|
|
421
|
+ filter interface{},
|
|
|
422
|
+ skip, limit int64,
|
|
|
423
|
+ sort interface{},
|
|
|
424
|
+ results interface{},
|
|
|
425
|
+) error {
|
|
|
426
|
+ //collection := f.GetCollection(collectionName)
|
|
|
427
|
+ //ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
428
|
+ //defer cancel()
|
|
|
429
|
+
|
|
|
430
|
+ findOptions := options.Find().
|
|
|
431
|
+ SetSkip(skip).
|
|
|
432
|
+ SetLimit(limit)
|
|
|
433
|
+
|
|
|
434
|
+ if sort != nil {
|
|
|
435
|
+ findOptions.SetSort(sort)
|
|
|
436
|
+ }
|
|
|
437
|
+
|
|
|
438
|
+ return f.Find(collectionName, filter, results, findOptions)
|
|
|
439
|
+}
|
|
|
440
|
+
|
|
|
441
|
+// FindOneByID 根据ID查询文档
|
|
|
442
|
+func (f *MongoDBFactory) FindOneByID(collectionName string, id interface{}, result interface{}) error {
|
|
|
443
|
+ return f.FindOne(collectionName, bson.M{"_id": id}, result)
|
|
|
444
|
+}
|
|
|
445
|
+
|
|
|
446
|
+// Exists 检查文档是否存在
|
|
|
447
|
+func (f *MongoDBFactory) Exists(collectionName string, filter interface{}) (bool, error) {
|
|
|
448
|
+ count, err := f.CountDocuments(collectionName, filter)
|
|
|
449
|
+ if err != nil {
|
|
|
450
|
+ return false, err
|
|
|
451
|
+ }
|
|
|
452
|
+ return count > 0, nil
|
|
|
453
|
+}
|
|
|
454
|
+
|
|
|
455
|
+// FindAndCount 查询文档并返回总数(用于分页场景)
|
|
|
456
|
+func (f *MongoDBFactory) FindAndCount(
|
|
|
457
|
+ collectionName string,
|
|
|
458
|
+ filter interface{},
|
|
|
459
|
+ skip, limit int64,
|
|
|
460
|
+ sort interface{},
|
|
|
461
|
+ results interface{},
|
|
|
462
|
+) (int64, error) {
|
|
|
463
|
+ // 查询数据
|
|
|
464
|
+ err := f.FindWithPagination(collectionName, filter, skip, limit, sort, results)
|
|
|
465
|
+ if err != nil {
|
|
|
466
|
+ return 0, err
|
|
|
467
|
+ }
|
|
|
468
|
+
|
|
|
469
|
+ // 查询总数
|
|
|
470
|
+ total, err := f.CountDocuments(collectionName, filter)
|
|
|
471
|
+ if err != nil {
|
|
|
472
|
+ return 0, err
|
|
|
473
|
+ }
|
|
|
474
|
+
|
|
|
475
|
+ return total, nil
|
|
|
476
|
+}
|
|
|
477
|
+
|
|
|
478
|
+// UpdateOne 更新单个文档,返回是否执行成功和影响记录数
|
|
|
479
|
+func (f *MongoDBFactory) UpdateOne(collectionName string, filter interface{}, update interface{}) (bool, int64) {
|
|
|
480
|
+ collection := f.GetCollection(collectionName)
|
|
|
481
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
482
|
+ defer cancel()
|
|
|
483
|
+
|
|
|
484
|
+ result, err := collection.UpdateOne(ctx, filter, update)
|
|
|
485
|
+ if err != nil {
|
|
|
486
|
+ logger.Errorf("更新文档失败,集合:%s,过滤条件:%v,错误:%v", collectionName, filter, err)
|
|
|
487
|
+ return false, 0
|
|
|
488
|
+ }
|
|
|
489
|
+
|
|
|
490
|
+ // 返回执行成功 和 实际更新的文档数
|
|
|
491
|
+ return true, result.ModifiedCount
|
|
|
492
|
+}
|
|
|
493
|
+
|
|
|
494
|
+// UpdateOneWithMatch 更新单个文档,只有匹配到文档才返回成功
|
|
|
495
|
+func (f *MongoDBFactory) UpdateOneWithMatch(collectionName string, filter interface{}, update interface{}) bool {
|
|
|
496
|
+ success, modifiedCount := f.UpdateOne(collectionName, filter, update)
|
|
|
497
|
+ return success && modifiedCount > 0
|
|
|
498
|
+}
|
|
|
499
|
+
|
|
|
500
|
+// UpdateMany 更新多个文档,返回是否执行成功和影响记录数
|
|
|
501
|
+func (f *MongoDBFactory) UpdateMany(collectionName string, filter interface{}, update interface{}) (bool, int64) {
|
|
|
502
|
+ collection := f.GetCollection(collectionName)
|
|
|
503
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
504
|
+ defer cancel()
|
|
|
505
|
+
|
|
|
506
|
+ result, err := collection.UpdateMany(ctx, filter, update)
|
|
|
507
|
+ if err != nil {
|
|
|
508
|
+ logger.Errorf("批量更新文档失败,集合:%s,过滤条件:%v,错误:%v", collectionName, filter, err)
|
|
|
509
|
+ return false, 0
|
|
|
510
|
+ }
|
|
|
511
|
+
|
|
|
512
|
+ return true, result.ModifiedCount
|
|
|
513
|
+}
|
|
|
514
|
+
|
|
|
515
|
+// DeleteOne 删除单个文档,返回是否执行成功和删除的记录数
|
|
|
516
|
+func (f *MongoDBFactory) DeleteOne(collectionName string, filter interface{}) (bool, int64) {
|
|
|
517
|
+ collection := f.GetCollection(collectionName)
|
|
|
518
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
519
|
+ defer cancel()
|
|
|
520
|
+
|
|
|
521
|
+ result, err := collection.DeleteOne(ctx, filter)
|
|
|
522
|
+ if err != nil {
|
|
|
523
|
+ logger.Errorf("删除文档失败,集合:%s,过滤条件:%v,错误:%v", collectionName, filter, err)
|
|
|
524
|
+ return false, 0
|
|
|
525
|
+ }
|
|
|
526
|
+
|
|
|
527
|
+ // 返回执行成功 和 实际删除的文档数
|
|
|
528
|
+ return true, result.DeletedCount
|
|
|
529
|
+}
|
|
|
530
|
+
|
|
|
531
|
+// DeleteOneWithMatch 删除单个文档,只有删除了文档才返回成功
|
|
|
532
|
+func (f *MongoDBFactory) DeleteOneWithMatch(collectionName string, filter interface{}) bool {
|
|
|
533
|
+ success, deletedCount := f.DeleteOne(collectionName, filter)
|
|
|
534
|
+ return success && deletedCount > 0
|
|
|
535
|
+}
|
|
|
536
|
+
|
|
|
537
|
+// DeleteMany 删除多个文档,返回是否执行成功和删除的记录数
|
|
|
538
|
+func (f *MongoDBFactory) DeleteMany(collectionName string, filter interface{}) (bool, int64) {
|
|
|
539
|
+ collection := f.GetCollection(collectionName)
|
|
|
540
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
541
|
+ defer cancel()
|
|
|
542
|
+
|
|
|
543
|
+ result, err := collection.DeleteMany(ctx, filter)
|
|
|
544
|
+ if err != nil {
|
|
|
545
|
+ logger.Errorf("批量删除文档失败,集合:%s,过滤条件:%v,错误:%v", collectionName, filter, err)
|
|
|
546
|
+ return false, 0
|
|
|
547
|
+ }
|
|
|
548
|
+
|
|
|
549
|
+ return true, result.DeletedCount
|
|
|
550
|
+}
|
|
|
551
|
+
|
|
|
552
|
+// UpsertOne 更新或插入文档(upsert操作)
|
|
|
553
|
+func (f *MongoDBFactory) UpsertOne(collectionName string, filter interface{}, update interface{}) (bool, interface{}) {
|
|
|
554
|
+ collection := f.GetCollection(collectionName)
|
|
|
555
|
+ ctx, cancel := context.WithTimeout(context.Background(), f.config.Timeout)
|
|
|
556
|
+ defer cancel()
|
|
|
557
|
+
|
|
|
558
|
+ // 设置 upsert 选项
|
|
|
559
|
+ opts := options.Update().SetUpsert(true)
|
|
|
560
|
+
|
|
|
561
|
+ result, err := collection.UpdateOne(ctx, filter, update, opts)
|
|
|
562
|
+ if err != nil {
|
|
|
563
|
+ logger.Errorf("Upsert操作失败,集合:%s,过滤条件:%v,错误:%v", collectionName, filter, err)
|
|
|
564
|
+ return false, result
|
|
|
565
|
+ }
|
|
|
566
|
+
|
|
|
567
|
+ // 返回: 成功状态, 匹配数, 修改数, 插入数
|
|
|
568
|
+ return true, result
|
|
|
569
|
+}
|
|
|
570
|
+
|
|
|
571
|
+// UpdateOneByID 根据ID更新文档
|
|
|
572
|
+func (f *MongoDBFactory) UpdateOneByID(collectionName string, id interface{}, update interface{}) (bool, int64) {
|
|
|
573
|
+ return f.UpdateOne(collectionName, bson.M{"_id": id}, update)
|
|
|
574
|
+}
|
|
|
575
|
+
|
|
|
576
|
+// UpdateOneByIDWithMatch 根据ID更新文档,只有匹配到才返回成功
|
|
|
577
|
+func (f *MongoDBFactory) UpdateOneByIDWithMatch(collectionName string, id interface{}, update interface{}) bool {
|
|
|
578
|
+ success, modifiedCount := f.UpdateOneByID(collectionName, id, update)
|
|
|
579
|
+ return success && modifiedCount > 0
|
|
|
580
|
+}
|
|
|
581
|
+
|
|
|
582
|
+// DeleteOneByID 根据ID删除文档
|
|
|
583
|
+func (f *MongoDBFactory) DeleteOneByID(collectionName string, id interface{}) (bool, int64) {
|
|
|
584
|
+ return f.DeleteOne(collectionName, bson.M{"_id": id})
|
|
|
585
|
+}
|
|
|
586
|
+
|
|
|
587
|
+// DeleteOneByIDWithMatch 根据ID删除文档,只有删除了才返回成功
|
|
|
588
|
+func (f *MongoDBFactory) DeleteOneByIDWithMatch(collectionName string, id interface{}) bool {
|
|
|
589
|
+ success, deletedCount := f.DeleteOneByID(collectionName, id)
|
|
|
590
|
+ return success && deletedCount > 0
|
|
|
591
|
+}
|