-
Notifications
You must be signed in to change notification settings - Fork 892
/
collection.go
2158 lines (1911 loc) · 65.6 KB
/
collection.go
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package mongo
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"time"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/internal/csfle"
"go.mongodb.org/mongo-driver/v2/internal/mongoutil"
"go.mongodb.org/mongo-driver/v2/internal/serverselector"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"go.mongodb.org/mongo-driver/v2/mongo/readconcern"
"go.mongodb.org/mongo-driver/v2/mongo/readpref"
"go.mongodb.org/mongo-driver/v2/mongo/writeconcern"
"go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/v2/x/mongo/driver"
"go.mongodb.org/mongo-driver/v2/x/mongo/driver/description"
"go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation"
"go.mongodb.org/mongo-driver/v2/x/mongo/driver/session"
)
// Collection is a handle to a MongoDB collection. It is safe for concurrent use by multiple goroutines.
type Collection struct {
client *Client
db *Database
name string
readConcern *readconcern.ReadConcern
writeConcern *writeconcern.WriteConcern
readPreference *readpref.ReadPref
readSelector description.ServerSelector
writeSelector description.ServerSelector
bsonOpts *options.BSONOptions
registry *bson.Registry
}
// aggregateParams is used to store information to configure an Aggregate operation.
type aggregateParams struct {
ctx context.Context
pipeline interface{}
client *Client
bsonOpts *options.BSONOptions
registry *bson.Registry
readConcern *readconcern.ReadConcern
writeConcern *writeconcern.WriteConcern
retryRead bool
db string
col string
readSelector description.ServerSelector
writeSelector description.ServerSelector
readPreference *readpref.ReadPref
}
func closeImplicitSession(sess *session.Client) {
if sess != nil && sess.IsImplicit {
sess.EndSession()
}
}
func newCollection(db *Database, name string, opts ...options.Lister[options.CollectionOptions]) *Collection {
args, _ := mongoutil.NewOptions[options.CollectionOptions](opts...)
rc := db.readConcern
if args.ReadConcern != nil {
rc = args.ReadConcern
}
wc := db.writeConcern
if args.WriteConcern != nil {
wc = args.WriteConcern
}
rp := db.readPreference
if args.ReadPreference != nil {
rp = args.ReadPreference
}
bsonOpts := db.bsonOpts
if args.BSONOptions != nil {
bsonOpts = args.BSONOptions
}
reg := db.registry
if args.Registry != nil {
reg = args.Registry
}
readSelector := &serverselector.Composite{
Selectors: []description.ServerSelector{
&serverselector.ReadPref{ReadPref: rp},
&serverselector.Latency{Latency: db.client.localThreshold},
},
}
writeSelector := &serverselector.Composite{
Selectors: []description.ServerSelector{
&serverselector.Write{},
&serverselector.Latency{Latency: db.client.localThreshold},
},
}
coll := &Collection{
client: db.client,
db: db,
name: name,
readPreference: rp,
readConcern: rc,
writeConcern: wc,
readSelector: readSelector,
writeSelector: writeSelector,
bsonOpts: bsonOpts,
registry: reg,
}
return coll
}
func (coll *Collection) copy() *Collection {
return &Collection{
client: coll.client,
db: coll.db,
name: coll.name,
readConcern: coll.readConcern,
writeConcern: coll.writeConcern,
readPreference: coll.readPreference,
readSelector: coll.readSelector,
writeSelector: coll.writeSelector,
registry: coll.registry,
}
}
// Clone creates a copy of the Collection configured with the given CollectionOptions.
// The specified options are merged with the existing options on the collection, with the specified options taking
// precedence.
func (coll *Collection) Clone(opts ...options.Lister[options.CollectionOptions]) *Collection {
copyColl := coll.copy()
args, _ := mongoutil.NewOptions[options.CollectionOptions](opts...)
if args.ReadConcern != nil {
copyColl.readConcern = args.ReadConcern
}
if args.WriteConcern != nil {
copyColl.writeConcern = args.WriteConcern
}
if args.ReadPreference != nil {
copyColl.readPreference = args.ReadPreference
}
if args.Registry != nil {
copyColl.registry = args.Registry
}
copyColl.readSelector = &serverselector.Composite{
Selectors: []description.ServerSelector{
&serverselector.ReadPref{ReadPref: copyColl.readPreference},
&serverselector.Latency{Latency: copyColl.client.localThreshold},
},
}
return copyColl
}
// Name returns the name of the collection.
func (coll *Collection) Name() string {
return coll.name
}
// Database returns the Database that was used to create the Collection.
func (coll *Collection) Database() *Database {
return coll.db
}
// BulkWrite performs a bulk write operation (https://www.mongodb.com/docs/manual/core/bulk-write-operations/).
//
// The models parameter must be a slice of operations to be executed in this bulk write. It cannot be nil or empty.
// All of the models must be non-nil. See the mongo.WriteModel documentation for a list of valid model types and
// examples of how they should be used.
//
// The opts parameter can be used to specify options for the operation (see the options.BulkWriteOptions documentation.)
func (coll *Collection) BulkWrite(ctx context.Context, models []WriteModel,
opts ...options.Lister[options.BulkWriteOptions]) (*BulkWriteResult, error) {
if len(models) == 0 {
return nil, ErrEmptySlice
}
if ctx == nil {
ctx = context.Background()
}
sess := sessionFromContext(ctx)
if sess == nil && coll.client.sessionPool != nil {
sess = session.NewImplicitClientSession(coll.client.sessionPool, coll.client.id)
defer sess.EndSession()
}
err := coll.client.validSession(sess)
if err != nil {
return nil, err
}
wc := coll.writeConcern
if sess.TransactionRunning() {
wc = nil
}
if !wc.Acknowledged() {
sess = nil
}
selector := makePinnedSelector(sess, coll.writeSelector)
for _, model := range models {
if model == nil {
return nil, ErrNilDocument
}
}
// Ensure opts have the default case at the front.
opts = append([]options.Lister[options.BulkWriteOptions]{options.BulkWrite()}, opts...)
args, err := mongoutil.NewOptions(opts...)
if err != nil {
return nil, err
}
op := bulkWrite{
comment: args.Comment,
ordered: args.Ordered,
bypassDocumentValidation: args.BypassDocumentValidation,
models: models,
session: sess,
collection: coll,
selector: selector,
writeConcern: wc,
let: args.Let,
}
err = op.execute(ctx)
return &op.result, replaceErrors(err)
}
func (coll *Collection) insert(
ctx context.Context,
documents []interface{},
opts ...options.Lister[options.InsertManyOptions],
) ([]interface{}, error) {
if ctx == nil {
ctx = context.Background()
}
result := make([]interface{}, len(documents))
docs := make([]bsoncore.Document, len(documents))
for i, doc := range documents {
bsoncoreDoc, err := marshal(doc, coll.bsonOpts, coll.registry)
if err != nil {
return nil, err
}
bsoncoreDoc, id, err := ensureID(bsoncoreDoc, bson.NilObjectID, coll.bsonOpts, coll.registry)
if err != nil {
return nil, err
}
docs[i] = bsoncoreDoc
result[i] = id
}
sess := sessionFromContext(ctx)
if sess == nil && coll.client.sessionPool != nil {
sess = session.NewImplicitClientSession(coll.client.sessionPool, coll.client.id)
defer sess.EndSession()
}
err := coll.client.validSession(sess)
if err != nil {
return nil, err
}
wc := coll.writeConcern
if sess.TransactionRunning() {
wc = nil
}
if !wc.Acknowledged() {
sess = nil
}
selector := makePinnedSelector(sess, coll.writeSelector)
op := operation.NewInsert(docs...).
Session(sess).WriteConcern(wc).CommandMonitor(coll.client.monitor).
ServerSelector(selector).ClusterClock(coll.client.clock).
Database(coll.db.name).Collection(coll.name).
Deployment(coll.client.deployment).Crypt(coll.client.cryptFLE).Ordered(true).
ServerAPI(coll.client.serverAPI).Timeout(coll.client.timeout).Logger(coll.client.logger).Authenticator(coll.client.authenticator)
args, err := mongoutil.NewOptions[options.InsertManyOptions](opts...)
if err != nil {
return nil, fmt.Errorf("failed to construct options from builder: %w", err)
}
if args.BypassDocumentValidation != nil && *args.BypassDocumentValidation {
op = op.BypassDocumentValidation(*args.BypassDocumentValidation)
}
if args.Comment != nil {
comment, err := marshalValue(args.Comment, coll.bsonOpts, coll.registry)
if err != nil {
return nil, err
}
op = op.Comment(comment)
}
if args.Ordered != nil {
op = op.Ordered(*args.Ordered)
}
retry := driver.RetryNone
if coll.client.retryWrites {
retry = driver.RetryOncePerCommand
}
op = op.Retry(retry)
err = op.Execute(ctx)
var wce driver.WriteCommandError
if !errors.As(err, &wce) {
return result, err
}
// remove the ids that had writeErrors from result
for i, we := range wce.WriteErrors {
// i indexes have been removed before the current error, so the index is we.Index-i
idIndex := int(we.Index) - i
// if the insert is ordered, nothing after the error was inserted
if args.Ordered == nil || *args.Ordered {
result = result[:idIndex]
break
}
result = append(result[:idIndex], result[idIndex+1:]...)
}
return result, err
}
// InsertOne executes an insert command to insert a single document into the collection.
//
// The document parameter must be the document to be inserted. It cannot be nil. If the document does not have an _id
// field when transformed into BSON, one will be added automatically to the marshalled document. The original document
// will not be modified. The _id can be retrieved from the InsertedID field of the returned InsertOneResult.
//
// The opts parameter can be used to specify options for the operation (see the options.InsertOneOptions documentation.)
//
// For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/insert/.
func (coll *Collection) InsertOne(ctx context.Context, document interface{},
opts ...options.Lister[options.InsertOneOptions]) (*InsertOneResult, error) {
args, err := mongoutil.NewOptions(opts...)
if err != nil {
return nil, err
}
imOpts := options.InsertMany()
if args.BypassDocumentValidation != nil && *args.BypassDocumentValidation {
imOpts.SetBypassDocumentValidation(*args.BypassDocumentValidation)
}
if args.Comment != nil {
imOpts.SetComment(args.Comment)
}
res, err := coll.insert(ctx, []interface{}{document}, imOpts)
rr, err := processWriteError(err)
if rr&rrOne == 0 && rr.isAcknowledged() {
return nil, err
}
return &InsertOneResult{
InsertedID: res[0],
Acknowledged: rr.isAcknowledged(),
}, err
}
// InsertMany executes an insert command to insert multiple documents into the collection. If write errors occur
// during the operation (e.g. duplicate key error), this method returns a BulkWriteException error.
//
// The documents parameter must be a slice of documents to insert. The slice cannot be nil or empty. The elements must
// all be non-nil. For any document that does not have an _id field when transformed into BSON, one will be added
// automatically to the marshalled document. The original document will not be modified. The _id values for the inserted
// documents can be retrieved from the InsertedIDs field of the returned InsertManyResult.
//
// The opts parameter can be used to specify options for the operation (see the options.InsertManyOptions documentation.)
//
// For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/insert/.
func (coll *Collection) InsertMany(
ctx context.Context,
documents interface{},
opts ...options.Lister[options.InsertManyOptions],
) (*InsertManyResult, error) {
dv := reflect.ValueOf(documents)
if dv.Kind() != reflect.Slice {
return nil, ErrNotSlice
}
if dv.Len() == 0 {
return nil, ErrEmptySlice
}
docSlice := make([]interface{}, 0, dv.Len())
for i := 0; i < dv.Len(); i++ {
docSlice = append(docSlice, dv.Index(i).Interface())
}
result, err := coll.insert(ctx, docSlice, opts...)
rr, err := processWriteError(err)
if rr&rrMany == 0 {
return nil, err
}
imResult := &InsertManyResult{
InsertedIDs: result,
Acknowledged: rr.isAcknowledged(),
}
var writeException WriteException
if !errors.As(err, &writeException) {
return imResult, err
}
// create and return a BulkWriteException
bwErrors := make([]BulkWriteError, 0, len(writeException.WriteErrors))
for _, we := range writeException.WriteErrors {
bwErrors = append(bwErrors, BulkWriteError{
WriteError: we,
Request: nil,
})
}
return imResult, BulkWriteException{
WriteErrors: bwErrors,
WriteConcernError: writeException.WriteConcernError,
Labels: writeException.Labels,
}
}
func (coll *Collection) delete(
ctx context.Context,
filter interface{},
deleteOne bool,
expectedRr returnResult,
args *options.DeleteManyOptions,
) (*DeleteResult, error) {
if ctx == nil {
ctx = context.Background()
}
f, err := marshal(filter, coll.bsonOpts, coll.registry)
if err != nil {
return nil, err
}
sess := sessionFromContext(ctx)
if sess == nil && coll.client.sessionPool != nil {
sess = session.NewImplicitClientSession(coll.client.sessionPool, coll.client.id)
defer sess.EndSession()
}
err = coll.client.validSession(sess)
if err != nil {
return nil, err
}
wc := coll.writeConcern
if sess.TransactionRunning() {
wc = nil
}
if !wc.Acknowledged() {
sess = nil
}
selector := makePinnedSelector(sess, coll.writeSelector)
var limit int32
if deleteOne {
limit = 1
}
didx, doc := bsoncore.AppendDocumentStart(nil)
doc = bsoncore.AppendDocumentElement(doc, "q", f)
doc = bsoncore.AppendInt32Element(doc, "limit", limit)
if args.Collation != nil {
doc = bsoncore.AppendDocumentElement(doc, "collation", toDocument(args.Collation))
}
if args.Hint != nil {
if isUnorderedMap(args.Hint) {
return nil, ErrMapForOrderedArgument{"hint"}
}
hint, err := marshalValue(args.Hint, coll.bsonOpts, coll.registry)
if err != nil {
return nil, err
}
doc = bsoncore.AppendValueElement(doc, "hint", hint)
}
doc, _ = bsoncore.AppendDocumentEnd(doc, didx)
op := operation.NewDelete(doc).
Session(sess).WriteConcern(wc).CommandMonitor(coll.client.monitor).
ServerSelector(selector).ClusterClock(coll.client.clock).
Database(coll.db.name).Collection(coll.name).
Deployment(coll.client.deployment).Crypt(coll.client.cryptFLE).Ordered(true).
ServerAPI(coll.client.serverAPI).Timeout(coll.client.timeout).Logger(coll.client.logger).Authenticator(coll.client.authenticator)
if args.Comment != nil {
comment, err := marshalValue(args.Comment, coll.bsonOpts, coll.registry)
if err != nil {
return nil, err
}
op = op.Comment(comment)
}
if args.Hint != nil {
op = op.Hint(true)
}
if args.Let != nil {
let, err := marshal(args.Let, coll.bsonOpts, coll.registry)
if err != nil {
return nil, err
}
op = op.Let(let)
}
// deleteMany cannot be retried
retryMode := driver.RetryNone
if deleteOne && coll.client.retryWrites {
retryMode = driver.RetryOncePerCommand
}
op = op.Retry(retryMode)
rr, err := processWriteError(op.Execute(ctx))
if rr&expectedRr == 0 {
return nil, err
}
return &DeleteResult{
DeletedCount: op.Result().N,
Acknowledged: rr.isAcknowledged(),
}, err
}
// DeleteOne executes a delete command to delete at most one document from the collection.
//
// The filter parameter must be a document containing query operators and can be used to select the document to be
// deleted. It cannot be nil. If the filter does not match any documents, the operation will succeed and a DeleteResult
// with a DeletedCount of 0 will be returned. If the filter matches multiple documents, one will be selected from the
// matched set.
//
// The opts parameter can be used to specify options for the operation (see the options.DeleteOptions documentation).
//
// For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/delete/.
func (coll *Collection) DeleteOne(
ctx context.Context,
filter interface{},
opts ...options.Lister[options.DeleteOneOptions],
) (*DeleteResult, error) {
args, err := mongoutil.NewOptions[options.DeleteOneOptions](opts...)
if err != nil {
return nil, fmt.Errorf("failed to construct options from builder: %w", err)
}
deleteOptions := &options.DeleteManyOptions{
Collation: args.Collation,
Comment: args.Comment,
Hint: args.Hint,
Let: args.Let,
}
return coll.delete(ctx, filter, true, rrOne, deleteOptions)
}
// DeleteMany executes a delete command to delete documents from the collection.
//
// The filter parameter must be a document containing query operators and can be used to select the documents to
// be deleted. It cannot be nil. An empty document (e.g. bson.D{}) should be used to delete all documents in the
// collection. If the filter does not match any documents, the operation will succeed and a DeleteResult with a
// DeletedCount of 0 will be returned.
//
// The opts parameter can be used to specify options for the operation (see the options.DeleteOptions documentation).
//
// For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/delete/.
func (coll *Collection) DeleteMany(
ctx context.Context,
filter interface{},
opts ...options.Lister[options.DeleteManyOptions],
) (*DeleteResult, error) {
args, err := mongoutil.NewOptions[options.DeleteManyOptions](opts...)
if err != nil {
return nil, fmt.Errorf("failed to construct options from builder: %w", err)
}
return coll.delete(ctx, filter, false, rrMany, args)
}
func (coll *Collection) updateOrReplace(
ctx context.Context,
filter bsoncore.Document,
update interface{},
multi bool,
expectedRr returnResult,
checkDollarKey bool,
args *options.UpdateManyOptions,
) (*UpdateResult, error) {
if ctx == nil {
ctx = context.Background()
}
// collation, arrayFilters, upsert, and hint are included on the individual update documents rather than as part of the
// command
updateDoc, err := updateDoc{
filter: filter,
update: update,
hint: args.Hint,
arrayFilters: args.ArrayFilters,
collation: args.Collation,
upsert: args.Upsert,
multi: multi,
checkDollarKey: checkDollarKey,
}.marshal(coll.bsonOpts, coll.registry)
if err != nil {
return nil, err
}
sess := sessionFromContext(ctx)
if sess == nil && coll.client.sessionPool != nil {
sess = session.NewImplicitClientSession(coll.client.sessionPool, coll.client.id)
defer sess.EndSession()
}
err = coll.client.validSession(sess)
if err != nil {
return nil, err
}
wc := coll.writeConcern
if sess.TransactionRunning() {
wc = nil
}
if !wc.Acknowledged() {
sess = nil
}
selector := makePinnedSelector(sess, coll.writeSelector)
op := operation.NewUpdate(updateDoc).
Session(sess).WriteConcern(wc).CommandMonitor(coll.client.monitor).
ServerSelector(selector).ClusterClock(coll.client.clock).
Database(coll.db.name).Collection(coll.name).
Deployment(coll.client.deployment).Crypt(coll.client.cryptFLE).Hint(args.Hint != nil).
ArrayFilters(args.ArrayFilters != nil).Ordered(true).ServerAPI(coll.client.serverAPI).
Timeout(coll.client.timeout).Logger(coll.client.logger).Authenticator(coll.client.authenticator)
if args.Let != nil {
let, err := marshal(args.Let, coll.bsonOpts, coll.registry)
if err != nil {
return nil, err
}
op = op.Let(let)
}
if args.BypassDocumentValidation != nil && *args.BypassDocumentValidation {
op = op.BypassDocumentValidation(*args.BypassDocumentValidation)
}
if args.Comment != nil {
comment, err := marshalValue(args.Comment, coll.bsonOpts, coll.registry)
if err != nil {
return nil, err
}
op = op.Comment(comment)
}
retry := driver.RetryNone
// retryable writes are only enabled updateOne/replaceOne operations
if !multi && coll.client.retryWrites {
retry = driver.RetryOncePerCommand
}
op = op.Retry(retry)
err = op.Execute(ctx)
rr, err := processWriteError(err)
if rr&expectedRr == 0 {
return nil, err
}
opRes := op.Result()
res := &UpdateResult{
MatchedCount: opRes.N,
ModifiedCount: opRes.NModified,
UpsertedCount: int64(len(opRes.Upserted)),
Acknowledged: rr.isAcknowledged(),
}
if len(opRes.Upserted) > 0 {
res.UpsertedID = opRes.Upserted[0].ID
res.MatchedCount--
}
return res, err
}
// UpdateByID executes an update command to update the document whose _id value matches the provided ID in the collection.
// This is equivalent to running UpdateOne(ctx, bson.D{{"_id", id}}, update, opts...).
//
// The id parameter is the _id of the document to be updated. It cannot be nil. If the ID does not match any documents,
// the operation will succeed and an UpdateResult with a MatchedCount of 0 will be returned.
//
// The update parameter must be a document containing update operators
// (https://www.mongodb.com/docs/manual/reference/operator/update/) and can be used to specify the modifications to be
// made to the selected document. It cannot be nil or empty.
//
// The opts parameter can be used to specify options for the operation (see the options.UpdateOptions documentation).
//
// For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/update/.
func (coll *Collection) UpdateByID(
ctx context.Context,
id interface{},
update interface{},
opts ...options.Lister[options.UpdateOneOptions],
) (*UpdateResult, error) {
if id == nil {
return nil, ErrNilValue
}
return coll.UpdateOne(ctx, bson.D{{"_id", id}}, update, opts...)
}
// UpdateOne executes an update command to update at most one document in the collection.
//
// The filter parameter must be a document containing query operators and can be used to select the document to be
// updated. It cannot be nil. If the filter does not match any documents, the operation will succeed and an UpdateResult
// with a MatchedCount of 0 will be returned. If the filter matches multiple documents, one will be selected from the
// matched set and MatchedCount will equal 1.
//
// The update parameter must be a document containing update operators
// (https://www.mongodb.com/docs/manual/reference/operator/update/) and can be used to specify the modifications to be
// made to the selected document. It cannot be nil or empty.
//
// The opts parameter can be used to specify options for the operation (see the options.UpdateOptions documentation).
//
// For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/update/.
func (coll *Collection) UpdateOne(
ctx context.Context,
filter interface{},
update interface{},
opts ...options.Lister[options.UpdateOneOptions],
) (*UpdateResult, error) {
if ctx == nil {
ctx = context.Background()
}
f, err := marshal(filter, coll.bsonOpts, coll.registry)
if err != nil {
return nil, err
}
args, err := mongoutil.NewOptions[options.UpdateOneOptions](opts...)
if err != nil {
return nil, fmt.Errorf("failed to construct options from builder: %w", err)
}
updateOptions := &options.UpdateManyOptions{
ArrayFilters: args.ArrayFilters,
BypassDocumentValidation: args.BypassDocumentValidation,
Collation: args.Collation,
Comment: args.Comment,
Hint: args.Hint,
Upsert: args.Upsert,
Let: args.Let,
}
return coll.updateOrReplace(ctx, f, update, false, rrOne, true, updateOptions)
}
// UpdateMany executes an update command to update documents in the collection.
//
// The filter parameter must be a document containing query operators and can be used to select the documents to be
// updated. It cannot be nil. If the filter does not match any documents, the operation will succeed and an UpdateResult
// with a MatchedCount of 0 will be returned.
//
// The update parameter must be a document containing update operators
// (https://www.mongodb.com/docs/manual/reference/operator/update/) and can be used to specify the modifications to be made
// to the selected documents. It cannot be nil or empty.
//
// The opts parameter can be used to specify options for the operation (see the options.UpdateOptions documentation).
//
// For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/update/.
func (coll *Collection) UpdateMany(
ctx context.Context,
filter interface{},
update interface{},
opts ...options.Lister[options.UpdateManyOptions],
) (*UpdateResult, error) {
if ctx == nil {
ctx = context.Background()
}
f, err := marshal(filter, coll.bsonOpts, coll.registry)
if err != nil {
return nil, err
}
args, err := mongoutil.NewOptions[options.UpdateManyOptions](opts...)
if err != nil {
return nil, fmt.Errorf("failed to construct options from builder: %w", err)
}
return coll.updateOrReplace(ctx, f, update, true, rrMany, true, args)
}
// ReplaceOne executes an update command to replace at most one document in the collection.
//
// The filter parameter must be a document containing query operators and can be used to select the document to be
// replaced. It cannot be nil. If the filter does not match any documents, the operation will succeed and an
// UpdateResult with a MatchedCount of 0 will be returned. If the filter matches multiple documents, one will be
// selected from the matched set and MatchedCount will equal 1.
//
// The replacement parameter must be a document that will be used to replace the selected document. It cannot be nil
// and cannot contain any update operators (https://www.mongodb.com/docs/manual/reference/operator/update/).
//
// The opts parameter can be used to specify options for the operation (see the options.ReplaceOptions documentation).
//
// For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/update/.
func (coll *Collection) ReplaceOne(
ctx context.Context,
filter interface{},
replacement interface{},
opts ...options.Lister[options.ReplaceOptions],
) (*UpdateResult, error) {
if ctx == nil {
ctx = context.Background()
}
args, err := mongoutil.NewOptions[options.ReplaceOptions](opts...)
if err != nil {
return nil, fmt.Errorf("failed to construct options from builder: %w", err)
}
f, err := marshal(filter, coll.bsonOpts, coll.registry)
if err != nil {
return nil, err
}
r, err := marshal(replacement, coll.bsonOpts, coll.registry)
if err != nil {
return nil, err
}
if err := ensureNoDollarKey(r); err != nil {
return nil, err
}
updateOptions := &options.UpdateManyOptions{
BypassDocumentValidation: args.BypassDocumentValidation,
Collation: args.Collation,
Upsert: args.Upsert,
Hint: args.Hint,
Let: args.Let,
Comment: args.Comment,
}
return coll.updateOrReplace(ctx, f, r, false, rrOne, false, updateOptions)
}
// Aggregate executes an aggregate command against the collection and returns a cursor over the resulting documents.
//
// The pipeline parameter must be an array of documents, each representing an aggregation stage. The pipeline cannot
// be nil but can be empty. The stage documents must all be non-nil. For a pipeline of bson.D documents, the
// mongo.Pipeline type can be used. See
// https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/#db-collection-aggregate-stages for a list of
// valid stages in aggregations.
//
// The opts parameter can be used to specify options for the operation (see the options.AggregateOptions documentation.)
//
// For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/aggregate/.
func (coll *Collection) Aggregate(
ctx context.Context,
pipeline interface{},
opts ...options.Lister[options.AggregateOptions],
) (*Cursor, error) {
a := aggregateParams{
ctx: ctx,
pipeline: pipeline,
client: coll.client,
registry: coll.registry,
readConcern: coll.readConcern,
writeConcern: coll.writeConcern,
bsonOpts: coll.bsonOpts,
retryRead: coll.client.retryReads,
db: coll.db.name,
col: coll.name,
readSelector: coll.readSelector,
writeSelector: coll.writeSelector,
readPreference: coll.readPreference,
}
return aggregate(a, opts...)
}
// aggregate is the helper method for Aggregate
func aggregate(a aggregateParams, opts ...options.Lister[options.AggregateOptions]) (cur *Cursor, err error) {
if a.ctx == nil {
a.ctx = context.Background()
}
pipelineArr, hasOutputStage, err := marshalAggregatePipeline(a.pipeline, a.bsonOpts, a.registry)
if err != nil {
return nil, err
}
sess := sessionFromContext(a.ctx)
// Always close any created implicit sessions if aggregate returns an error.
defer func() {
if err != nil && sess != nil {
closeImplicitSession(sess)
}
}()
if sess == nil && a.client.sessionPool != nil {
sess = session.NewImplicitClientSession(a.client.sessionPool, a.client.id)
}
if err = a.client.validSession(sess); err != nil {
return nil, err
}
var wc *writeconcern.WriteConcern
if hasOutputStage {
wc = a.writeConcern
}
rc := a.readConcern
if sess.TransactionRunning() {
wc = nil
rc = nil
}
if !wc.Acknowledged() {
closeImplicitSession(sess)
sess = nil
}
selector := makeReadPrefSelector(sess, a.readSelector, a.client.localThreshold)
if hasOutputStage {
selector = makeOutputAggregateSelector(sess, a.readPreference, a.client.localThreshold)
}
args, err := mongoutil.NewOptions(opts...)
if err != nil {
return nil, err
}
cursorOpts := a.client.createBaseCursorOptions()
cursorOpts.MarshalValueEncoderFn = newEncoderFn(a.bsonOpts, a.registry)
op := operation.NewAggregate(pipelineArr).
Session(sess).
WriteConcern(wc).
ReadConcern(rc).
ReadPreference(a.readPreference).
CommandMonitor(a.client.monitor).
ServerSelector(selector).
ClusterClock(a.client.clock).
Database(a.db).
Collection(a.col).
Deployment(a.client.deployment).
Crypt(a.client.cryptFLE).
ServerAPI(a.client.serverAPI).
HasOutputStage(hasOutputStage).
Timeout(a.client.timeout).
Authenticator(a.client.authenticator).
// Omit "maxTimeMS" from operations that return a user-managed cursor to
// prevent confusing "cursor not found" errors.
//
// See DRIVERS-2722 for more detail.
OmitMaxTimeMS(true)
if args.AllowDiskUse != nil {
op.AllowDiskUse(*args.AllowDiskUse)
}
// ignore batchSize of 0 with $out
if args.BatchSize != nil && !(*args.BatchSize == 0 && hasOutputStage) {
op.BatchSize(*args.BatchSize)
cursorOpts.BatchSize = *args.BatchSize
}
if args.BypassDocumentValidation != nil && *args.BypassDocumentValidation {
op.BypassDocumentValidation(*args.BypassDocumentValidation)
}
if args.Collation != nil {
op.Collation(bsoncore.Document(toDocument(args.Collation)))
}
if args.MaxAwaitTime != nil {
cursorOpts.SetMaxAwaitTime(*args.MaxAwaitTime)
}
if args.Comment != nil {
comment, err := marshalValue(args.Comment, a.bsonOpts, a.registry)
if err != nil {