File: index_view_test.go

package info (click to toggle)
golang-mongodb-mongo-driver 1.17.1%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid, trixie
  • size: 25,988 kB
  • sloc: perl: 533; ansic: 491; python: 432; sh: 327; makefile: 174
file content (808 lines) | stat: -rw-r--r-- 28,348 bytes parent folder | download
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
// 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 integration

import (
	"context"
	"errors"
	"testing"
	"time"

	"github.com/google/go-cmp/cmp"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/internal/assert"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/integration/mtest"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/writeconcern"
	"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
)

type index struct {
	Key  bson.D
	Name string
}

func TestIndexView(t *testing.T) {
	mt := mtest.New(t, noClientOpts)

	var pbool = func(b bool) *bool { return &b }
	var pint32 = func(i int32) *int32 { return &i }

	mt.Run("list", func(mt *mtest.T) {
		createIndexes := func(mt *mtest.T, numIndexes int) {
			mt.Helper()

			models := make([]mongo.IndexModel, 0, numIndexes)
			for i, key := 0, 'a'; i < numIndexes; i, key = i+1, key+1 {
				models = append(models, mongo.IndexModel{
					Keys: bson.M{string(key): 1},
				})
			}

			_, err := mt.Coll.Indexes().CreateMany(context.Background(), models)
			assert.Nil(mt, err, "CreateMany error: %v", err)
		}

		// For server versions below 3.0, we internally execute List() as a legacy OP_QUERY against the system.indexes
		// collection. Command monitoring upconversions translate this to a "find" command rather than "listIndexes".
		cmdName := "listIndexes"
		if mtest.CompareServerVersions(mtest.ServerVersion(), "3.0") < 0 {
			cmdName = "find"
		}

		mt.Run("_id index is always listed", func(mt *mtest.T) {
			verifyIndexExists(mt, mt.Coll.Indexes(), index{
				Key:  bson.D{{"_id", int32(1)}},
				Name: "_id_",
			})
		})
		mt.Run("getMore commands are monitored", func(mt *mtest.T) {
			createIndexes(mt, 2)
			assertGetMoreCommandsAreMonitored(mt, cmdName, func() (*mongo.Cursor, error) {
				return mt.Coll.Indexes().List(context.Background(), options.ListIndexes().SetBatchSize(2))
			})
		})
		mt.Run("killCursors commands are monitored", func(mt *mtest.T) {
			createIndexes(mt, 2)
			assertKillCursorsCommandsAreMonitored(mt, cmdName, func() (*mongo.Cursor, error) {
				return mt.Coll.Indexes().List(context.Background(), options.ListIndexes().SetBatchSize(2))
			})
		})
	})
	mt.RunOpts("create one", noClientOpts, func(mt *mtest.T) {
		mt.Run("name not specified", func(mt *mtest.T) {
			iv := mt.Coll.Indexes()
			keysDoc := bson.D{
				{"foo", int32(1)},
				{"bar", int32(-1)},
			}
			expectedName := "foo_1_bar_-1"

			indexName, err := iv.CreateOne(context.Background(), mongo.IndexModel{
				Keys: keysDoc,
			})
			assert.Nil(mt, err, "CreateOne error: %v", err)
			assert.Equal(mt, expectedName, indexName, "expected name %q, got %q", expectedName, indexName)

			verifyIndexExists(mt, iv, index{
				Key:  keysDoc,
				Name: indexName,
			})
		})
		mt.Run("specify name", func(mt *mtest.T) {
			iv := mt.Coll.Indexes()
			keysDoc := bson.D{{"foo", int32(-1)}}
			name := "testname"

			indexName, err := iv.CreateOne(context.Background(), mongo.IndexModel{
				Keys:    keysDoc,
				Options: options.Index().SetName(name),
			})
			assert.Nil(mt, err, "CreateOne error: %v", err)
			assert.Equal(mt, name, indexName, "expected returned name %q, got %q", name, indexName)

			verifyIndexExists(mt, iv, index{
				Key:  keysDoc,
				Name: indexName,
			})
		})
		mt.Run("all options", func(mt *mtest.T) {
			opts := options.Index().
				SetBackground(false).
				SetExpireAfterSeconds(10).
				SetName("a").
				SetSparse(false).
				SetUnique(false).
				SetVersion(1).
				SetDefaultLanguage("english").
				SetLanguageOverride("english").
				SetTextVersion(1).
				SetWeights(bson.D{}).
				SetSphereVersion(1).
				SetBits(2).
				SetMax(10).
				SetMin(1).
				SetPartialFilterExpression(bson.D{}).
				SetStorageEngine(bson.D{
					{"wiredTiger", bson.D{
						{"configString", "block_compressor=zlib"},
					}},
				})

			// Only check SetBucketSize if version is less than 4.9
			if mtest.CompareServerVersions(mtest.ServerVersion(), "4.9") < 0 {
				opts.SetBucketSize(1)
			}
			// Omits collation option because it's incompatible with version option
			_, err := mt.Coll.Indexes().CreateOne(context.Background(), mongo.IndexModel{
				Keys:    bson.D{{"foo", "text"}},
				Options: opts,
			})
			assert.Nil(mt, err, "CreateOne error: %v", err)
		})
		mt.RunOpts("collation", mtest.NewOptions().MinServerVersion("3.4"), func(mt *mtest.T) {
			// collation invalid for server versions < 3.4
			_, err := mt.Coll.Indexes().CreateOne(context.Background(), mongo.IndexModel{
				Keys: bson.D{{"bar", "text"}},
				Options: options.Index().SetCollation(&options.Collation{
					Locale: "simple",
				}),
			})
			assert.Nil(mt, err, "CreateOne error: %v", err)
		})
		mt.RunOpts("wildcard", mtest.NewOptions().MinServerVersion("4.1").CreateClient(false), func(mt *mtest.T) {
			keysDoc := bson.D{{"$**", int32(1)}}

			mt.Run("no options", func(mt *mtest.T) {
				iv := mt.Coll.Indexes()
				indexName, err := iv.CreateOne(context.Background(), mongo.IndexModel{
					Keys: keysDoc,
				})
				assert.Nil(mt, err, "CreateOne error: %v", err)
				verifyIndexExists(mt, iv, index{
					Key:  keysDoc,
					Name: indexName,
				})
			})
			mt.Run("wildcard projection", func(mt *mtest.T) {
				iv := mt.Coll.Indexes()

				// Create an index with a wildcard projection document. The "_id: false" isn't needed to create the
				// index. We use the listIndexes command below to assert that the created index has this projection
				// document and the format of the document returned by listIndexes was changed in 4.5.x to explicitly
				// include "_id: false", so we include it here too.
				proj := bson.D{{"a", true}, {"_id", false}}
				_, err := iv.CreateOne(context.Background(), mongo.IndexModel{
					Keys:    keysDoc,
					Options: options.Index().SetWildcardProjection(proj),
				})
				assert.Nil(mt, err, "CreateOne error: %v", err)

				indexDoc := getIndexDoc(mt, iv, keysDoc)
				assert.NotNil(mt, indexDoc, "expected to find keys document %v but was not found", keysDoc)
				checkIndexDocContains(mt, indexDoc, bson.E{
					Key:   "wildcardProjection",
					Value: proj,
				})
			})
		})
		mt.RunOpts("hidden", mtest.NewOptions().MinServerVersion("4.4"), func(mt *mtest.T) {
			iv := mt.Coll.Indexes()
			keysDoc := bson.D{{"x", int32(1)}}
			model := mongo.IndexModel{
				Keys:    keysDoc,
				Options: options.Index().SetHidden(true),
			}

			_, err := iv.CreateOne(context.Background(), model)
			assert.Nil(mt, err, "CreateOne error: %v", err)

			indexDoc := getIndexDoc(mt, iv, keysDoc)
			assert.NotNil(mt, indexDoc, "index with keys document %v was not found", keysDoc)
			checkIndexDocContains(mt, indexDoc, bson.E{
				Key:   "hidden",
				Value: true,
			})
		})
		mt.Run("nil keys", func(mt *mtest.T) {
			_, err := mt.Coll.Indexes().CreateOne(context.Background(), mongo.IndexModel{
				Keys: nil,
			})
			assert.NotNil(mt, err, "expected CreateOne error, got nil")
		})
		// Only run on replica sets as commitQuorum is not supported on standalones.
		mt.RunOpts("commit quorum", mtest.NewOptions().Topologies(mtest.ReplicaSet).CreateClient(false), func(mt *mtest.T) {
			intVal := options.CreateIndexes().SetCommitQuorumInt(1)
			stringVal := options.CreateIndexes().SetCommitQuorumString("majority")
			majority := options.CreateIndexes().SetCommitQuorumMajority()
			votingMembers := options.CreateIndexes().SetCommitQuorumVotingMembers()

			indexModel := mongo.IndexModel{
				Keys: bson.D{{"x", 1}},
			}

			testCases := []struct {
				name             string
				opts             *options.CreateIndexesOptions
				expectError      bool
				expectedValue    interface{} // ignored if expectError is true
				minServerVersion string
				maxServerVersion string
			}{
				{"error on server versions before 4.4", majority, true, nil, "", "4.2"},
				{"integer value", intVal, false, int32(1), "4.4", ""},
				{"string value", stringVal, false, "majority", "4.4", ""},
				{"majority", majority, false, "majority", "4.4", ""},
				{"votingMembers", votingMembers, false, "votingMembers", "4.4", ""},
			}
			for _, tc := range testCases {
				mtOpts := mtest.NewOptions().MinServerVersion(tc.minServerVersion).MaxServerVersion(tc.maxServerVersion)
				mt.RunOpts(tc.name, mtOpts, func(mt *mtest.T) {
					mt.ClearEvents()
					_, err := mt.Coll.Indexes().CreateOne(context.Background(), indexModel, tc.opts)
					if tc.expectError {
						assert.NotNil(mt, err, "expected CreateOne error, got nil")
						return
					}

					assert.Nil(mt, err, "CreateOne error: %v", err)
					cmd := mt.GetStartedEvent().Command
					sentBSONValue, err := cmd.LookupErr("commitQuorum")
					assert.Nil(mt, err, "expected commitQuorum in command %s", cmd)

					var sentValue interface{}
					err = sentBSONValue.Unmarshal(&sentValue)
					assert.Nil(mt, err, "Unmarshal error: %v", err)

					assert.Equal(mt, tc.expectedValue, sentValue, "expected commitQuorum value %v, got %v",
						tc.expectedValue, sentValue)
				})
			}
		})
		unackClientOpts := options.Client().
			SetWriteConcern(writeconcern.New(writeconcern.W(0)))
		unackMtOpts := mtest.NewOptions().
			ClientOptions(unackClientOpts).
			MinServerVersion("3.6")
		mt.RunOpts("unacknowledged write", unackMtOpts, func(mt *mtest.T) {
			_, err := mt.Coll.Indexes().CreateOne(context.Background(), mongo.IndexModel{Keys: bson.D{{"x", 1}}})
			if !errors.Is(err, mongo.ErrUnacknowledgedWrite) {
				// Use a direct comparison rather than assert.Equal because assert.Equal will compare the error strings,
				// so the assertion would succeed even if the error had not been wrapped.
				mt.Fatalf("expected CreateOne error %v, got %v", mongo.ErrUnacknowledgedWrite, err)
			}
		})
		// Needs to run on these versions for failpoints
		mt.RunOpts("replace error", mtest.NewOptions().Topologies(mtest.ReplicaSet).MinServerVersion("4.0"), func(mt *mtest.T) {
			mt.SetFailPoint(mtest.FailPoint{
				ConfigureFailPoint: "failCommand",
				Mode:               "alwaysOn",
				Data: mtest.FailPointData{
					FailCommands: []string{"createIndexes"},
					ErrorCode:    100,
				},
			})

			_, err := mt.Coll.Indexes().CreateOne(context.Background(), mongo.IndexModel{Keys: bson.D{{"x", 1}}})
			assert.NotNil(mt, err, "expected CreateOne error, got nil")
			cmdErr, ok := err.(mongo.CommandError)
			assert.True(mt, ok, "expected mongo.CommandError, got %T", err)
			assert.Equal(mt, int32(100), cmdErr.Code, "expected error code 100, got %v", cmdErr.Code)

		})
		mt.Run("multi-key map", func(mt *mtest.T) {
			iv := mt.Coll.Indexes()

			_, err := iv.CreateOne(context.Background(), mongo.IndexModel{
				Keys: bson.M{"foo": 1, "bar": -1},
			})
			assert.NotNil(mt, err, "expected CreateOne error, got nil")
			assert.Equal(mt, mongo.ErrMapForOrderedArgument{"keys"}, err, "expected error %v, got %v", mongo.ErrMapForOrderedArgument{"key"}, err)
		})
		mt.Run("single key map", func(mt *mtest.T) {
			iv := mt.Coll.Indexes()
			expectedName := "foo_1"

			indexName, err := iv.CreateOne(context.Background(), mongo.IndexModel{
				Keys: bson.M{"foo": 1},
			})
			assert.Nil(mt, err, "CreateOne error: %v", err)
			assert.Equal(mt, expectedName, indexName, "expected name %q, got %q", expectedName, indexName)

			verifyIndexExists(mt, iv, index{
				Key:  bson.D{{"foo", int32(1)}},
				Name: indexName,
			})
		})
	})
	mt.Run("create many", func(mt *mtest.T) {
		mt.Run("success", func(mt *mtest.T) {
			iv := mt.Coll.Indexes()
			firstKeysDoc := bson.D{{"foo", int32(-1)}}
			secondKeysDoc := bson.D{{"bar", int32(1)}, {"baz", int32(-1)}}
			expectedNames := []string{"foo_-1", "bar_1_baz_-1"}
			indexNames, err := iv.CreateMany(context.Background(), []mongo.IndexModel{
				{
					Keys: firstKeysDoc,
				},
				{
					Keys: secondKeysDoc,
				},
			})
			assert.Nil(mt, err, "CreateMany error: %v", err)
			assert.Equal(mt, expectedNames, indexNames, "expected returned names %v, got %v", expectedNames, indexNames)

			verifyIndexExists(mt, iv, index{
				Key:  firstKeysDoc,
				Name: indexNames[0],
			})
			verifyIndexExists(mt, iv, index{
				Key:  secondKeysDoc,
				Name: indexNames[1],
			})
		})
		wc := writeconcern.New(writeconcern.W(1))
		wcMtOpts := mtest.NewOptions().CollectionOptions(options.Collection().SetWriteConcern(wc))
		mt.RunOpts("uses writeconcern", wcMtOpts, func(mt *mtest.T) {
			iv := mt.Coll.Indexes()
			_, err := iv.CreateMany(context.Background(), []mongo.IndexModel{
				{
					Keys: bson.D{{"foo", -1}},
				},
				{
					Keys: bson.D{{"bar", 1}, {"baz", -1}},
				},
			})
			assert.Nil(mt, err, "CreateMany error: %v", err)

			evt := mt.GetStartedEvent()
			assert.NotNil(mt, evt, "expected CommandStartedEvent, got nil")

			assert.Equal(mt, "createIndexes", evt.CommandName, "command name mismatch; expected createIndexes, got %s", evt.CommandName)

			actual, err := evt.Command.LookupErr("writeConcern", "w")
			assert.Nil(mt, err, "error getting writeConcern.w: %s", err)

			wcVal := numberFromValue(mt, actual)
			assert.Equal(mt, int64(1), wcVal, "expected writeConcern to be 1, got: %v", wcVal)
		})
		// Only run on replica sets as commitQuorum is not supported on standalones.
		mt.RunOpts("commit quorum", mtest.NewOptions().Topologies(mtest.ReplicaSet).CreateClient(false), func(mt *mtest.T) {
			intVal := options.CreateIndexes().SetCommitQuorumInt(1)
			stringVal := options.CreateIndexes().SetCommitQuorumString("majority")
			majority := options.CreateIndexes().SetCommitQuorumMajority()
			votingMembers := options.CreateIndexes().SetCommitQuorumVotingMembers()

			indexModel1 := mongo.IndexModel{
				Keys: bson.D{{"x", 1}},
			}
			indexModel2 := mongo.IndexModel{
				Keys: bson.D{{"y", 1}},
			}

			testCases := []struct {
				name             string
				opts             *options.CreateIndexesOptions
				expectError      bool
				expectedValue    interface{} // ignored if expectError is true
				minServerVersion string
				maxServerVersion string
			}{
				{"error on server versions before 4.4", majority, true, nil, "", "4.2"},
				{"integer value", intVal, false, int32(1), "4.4", ""},
				{"string value", stringVal, false, "majority", "4.4", ""},
				{"majority", majority, false, "majority", "4.4", ""},
				{"votingMembers", votingMembers, false, "votingMembers", "4.4", ""},
			}
			for _, tc := range testCases {
				mtOpts := mtest.NewOptions().MinServerVersion(tc.minServerVersion).MaxServerVersion(tc.maxServerVersion)
				mt.RunOpts(tc.name, mtOpts, func(mt *mtest.T) {
					mt.ClearEvents()
					_, err := mt.Coll.Indexes().CreateMany(context.Background(), []mongo.IndexModel{indexModel1, indexModel2}, tc.opts)
					if tc.expectError {
						assert.NotNil(mt, err, "expected CreateMany error, got nil")
						return
					}

					assert.Nil(mt, err, "CreateMany error: %v", err)
					cmd := mt.GetStartedEvent().Command
					sentBSONValue, err := cmd.LookupErr("commitQuorum")
					assert.Nil(mt, err, "expected commitQuorum in command %s", cmd)

					var sentValue interface{}
					err = sentBSONValue.Unmarshal(&sentValue)
					assert.Nil(mt, err, "Unmarshal error: %v", err)

					assert.Equal(mt, tc.expectedValue, sentValue, "expected commitQuorum value %v, got %v",
						tc.expectedValue, sentValue)
				})
			}
		})
		// Needs to run on these versions for failpoints
		mt.RunOpts("replace error", mtest.NewOptions().Topologies(mtest.ReplicaSet).MinServerVersion("4.0"), func(mt *mtest.T) {
			mt.SetFailPoint(mtest.FailPoint{
				ConfigureFailPoint: "failCommand",
				Mode:               "alwaysOn",
				Data: mtest.FailPointData{
					FailCommands: []string{"createIndexes"},
					ErrorCode:    100,
				},
			})

			_, err := mt.Coll.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
				{
					Keys: bson.D{{"foo", int32(-1)}},
				},
				{
					Keys: bson.D{{"bar", int32(1)}, {"baz", int32(-1)}},
				},
			})
			assert.NotNil(mt, err, "expected CreateMany error, got nil")
			cmdErr, ok := err.(mongo.CommandError)
			assert.True(mt, ok, "expected mongo.CommandError, got %T", err)
			assert.Equal(mt, int32(100), cmdErr.Code, "expected error code 100, got %v", cmdErr.Code)

		})
		mt.Run("multi-key map", func(mt *mtest.T) {
			iv := mt.Coll.Indexes()
			_, err := iv.CreateMany(context.Background(), []mongo.IndexModel{
				{
					Keys: bson.M{"foo": 1, "bar": -1},
				},
				{
					Keys: bson.D{{"bar", int32(1)}, {"baz", int32(-1)}},
				},
			})
			assert.NotNil(mt, err, "expected CreateOne error, got nil")
			assert.Equal(mt, mongo.ErrMapForOrderedArgument{"keys"}, err, "expected error %v, got %v", mongo.ErrMapForOrderedArgument{"keys"}, err)
		})
		mt.Run("single key map", func(mt *mtest.T) {
			iv := mt.Coll.Indexes()
			firstKeysDoc := bson.M{"foo": -1}
			secondKeysDoc := bson.D{{"bar", int32(1)}, {"baz", int32(-1)}}
			expectedNames := []string{"foo_-1", "bar_1_baz_-1"}
			indexNames, err := iv.CreateMany(context.Background(), []mongo.IndexModel{
				{
					Keys: firstKeysDoc,
				},
				{
					Keys: secondKeysDoc,
				},
			})
			assert.Nil(mt, err, "CreateMany error: %v", err)
			assert.Equal(mt, expectedNames, indexNames, "expected returned names %v, got %v", expectedNames, indexNames)

			verifyIndexExists(mt, iv, index{
				Key:  bson.D{{"foo", int32(-1)}},
				Name: indexNames[0],
			})
			verifyIndexExists(mt, iv, index{
				Key:  secondKeysDoc,
				Name: indexNames[1],
			})
		})
	})
	mt.RunOpts("list specifications", noClientOpts, func(mt *mtest.T) {
		mt.Run("verify results", func(mt *mtest.T) {
			// Create a handful of indexes
			_, err := mt.Coll.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
				{
					Keys:    bson.D{{"foo", int32(-1)}},
					Options: options.Index().SetUnique(true),
				},
				{
					Keys:    bson.D{{"bar", int32(1)}},
					Options: options.Index().SetExpireAfterSeconds(120),
				},
				{
					Keys:    bson.D{{"baz", int32(1)}},
					Options: options.Index().SetSparse(true),
				},
				{
					Keys: bson.D{{"bar", int32(1)}, {"baz", int32(-1)}},
				},
			})
			assert.Nil(mt, err, "CreateMany error: %v", err)

			expectedSpecs := []*mongo.IndexSpecification{
				{
					Name:               "_id_",
					Namespace:          mt.DB.Name() + "." + mt.Coll.Name(),
					KeysDocument:       bson.Raw(bsoncore.NewDocumentBuilder().AppendInt32("_id", 1).Build()),
					Version:            2,
					ExpireAfterSeconds: nil,
					Sparse:             nil,
					// ID index is special and does not return 'true', despite being unique.
					Unique: nil,
				},
				{
					Name:               "foo_-1",
					Namespace:          mt.DB.Name() + "." + mt.Coll.Name(),
					KeysDocument:       bson.Raw(bsoncore.NewDocumentBuilder().AppendInt32("foo", -1).Build()),
					Version:            2,
					ExpireAfterSeconds: nil,
					Sparse:             nil,
					Unique:             pbool(true),
				},
				{
					Name:               "bar_1",
					Namespace:          mt.DB.Name() + "." + mt.Coll.Name(),
					KeysDocument:       bson.Raw(bsoncore.NewDocumentBuilder().AppendInt32("bar", 1).Build()),
					Version:            2,
					ExpireAfterSeconds: pint32(120),
					Sparse:             nil,
					Unique:             nil,
				},
				{
					Name:               "baz_1",
					Namespace:          mt.DB.Name() + "." + mt.Coll.Name(),
					KeysDocument:       bson.Raw(bsoncore.NewDocumentBuilder().AppendInt32("baz", 1).Build()),
					Version:            2,
					ExpireAfterSeconds: nil,
					Sparse:             pbool(true),
					Unique:             nil,
				},
				{
					Name:               "bar_1_baz_-1",
					Namespace:          mt.DB.Name() + "." + mt.Coll.Name(),
					KeysDocument:       bson.Raw(bsoncore.NewDocumentBuilder().AppendInt32("bar", 1).AppendInt32("baz", -1).Build()),
					Version:            2,
					ExpireAfterSeconds: nil,
					Sparse:             nil,
					Unique:             nil,
				},
			}
			if mtest.CompareServerVersions(mtest.ServerVersion(), "3.4") < 0 {
				for _, expectedSpec := range expectedSpecs {
					expectedSpec.Version = 1
				}
			}

			specs, err := mt.Coll.Indexes().ListSpecifications(context.Background())
			assert.Nil(mt, err, "ListSpecifications error: %v", err)
			assert.Equal(mt, len(expectedSpecs), len(specs), "expected %d specification, got %d", len(expectedSpecs), len(specs))
			assert.True(mt, cmp.Equal(specs, expectedSpecs), "expected specifications to match: %v", cmp.Diff(specs, expectedSpecs))
		})
		mt.RunOpts("options passed to listIndexes", mtest.NewOptions().MinServerVersion("3.0"), func(mt *mtest.T) {
			opts := options.ListIndexes().SetMaxTime(100 * time.Millisecond)
			_, err := mt.Coll.Indexes().ListSpecifications(context.Background(), opts)
			assert.Nil(mt, err, "ListSpecifications error: %v", err)

			evt := mt.GetStartedEvent()
			assert.Equal(mt, evt.CommandName, "listIndexes", "expected %q command to be sent, got %q", "listIndexes",
				evt.CommandName)
			maxTimeMS, ok := evt.Command.Lookup("maxTimeMS").Int64OK()
			assert.True(mt, ok, "expected command %v to contain %q field", evt.Command, "maxTimeMS")
			assert.Equal(mt, int64(100), maxTimeMS, "expected maxTimeMS value to be 100, got %d", maxTimeMS)
		})
	})
	mt.Run("drop one", func(mt *mtest.T) {
		iv := mt.Coll.Indexes()
		indexNames, err := iv.CreateMany(context.Background(), []mongo.IndexModel{
			{
				Keys: bson.D{{"foo", -1}},
			},
			{
				Keys: bson.D{{"bar", 1}, {"baz", -1}},
			},
		})
		assert.Nil(mt, err, "CreateMany error: %v", err)
		assert.Equal(mt, 2, len(indexNames), "expected 2 index names, got %v", len(indexNames))

		_, err = iv.DropOne(context.Background(), indexNames[1])
		assert.Nil(mt, err, "DropOne error: %v", err)

		cursor, err := iv.List(context.Background())
		assert.Nil(mt, err, "List error: %v", err)
		for cursor.Next(context.Background()) {
			var idx index
			err = cursor.Decode(&idx)
			assert.Nil(mt, err, "Decode error: %v (document %v)", err, cursor.Current)
			assert.NotEqual(mt, indexNames[1], idx.Name, "found index %v after dropping", indexNames[1])
		}
		assert.Nil(mt, cursor.Err(), "cursor error: %v", cursor.Err())
	})
	mt.Run("drop with key", func(mt *mtest.T) {
		tests := []struct {
			name   string
			models []mongo.IndexModel
			index  any
			want   string
		}{
			{
				name: "custom index name and unique indexes",
				models: []mongo.IndexModel{
					{
						Keys:    bson.D{{"username", int32(1)}},
						Options: options.Index().SetUnique(true).SetName("myidx"),
					},
				},
				index: bson.D{{"username", int32(1)}},
				want:  "myidx",
			},
			{
				name: "normal generated index name",
				models: []mongo.IndexModel{
					{
						Keys: bson.D{{"foo", int32(-1)}},
					},
				},
				index: bson.D{{"foo", int32(-1)}},
				want:  "foo_-1",
			},
			{
				name: "compound index",
				models: []mongo.IndexModel{
					{
						Keys: bson.D{{"foo", int32(1)}, {"bar", int32(1)}},
					},
				},
				index: bson.D{{"foo", int32(1)}, {"bar", int32(1)}},
				want:  "foo_1_bar_1",
			},
			{
				name: "text index",
				models: []mongo.IndexModel{
					{
						Keys: bson.D{{"plot1", "text"}, {"plot2", "text"}},
					},
				},
				// Key is automatically set to Full Text Search for any text index
				index: bson.D{{"_fts", "text"}, {"_ftsx", int32(1)}},
				want:  "plot1_text_plot2_text",
			},
		}

		for _, test := range tests {
			mt.Run(test.name, func(mt *mtest.T) {
				iv := mt.Coll.Indexes()
				indexNames, err := iv.CreateMany(context.Background(), test.models)

				s, _ := test.index.(bson.D)
				for _, name := range indexNames {
					verifyIndexExists(mt, iv, index{
						Key:  s,
						Name: name,
					})
				}

				assert.NoError(mt, err)
				assert.Equal(mt, len(test.models), len(indexNames), "expected %v index names, got %v", len(test.models), len(indexNames))

				_, err = iv.DropOneWithKey(context.Background(), test.index)
				assert.Nil(mt, err, "DropOne error: %v", err)

				cursor, err := iv.List(context.Background())
				assert.Nil(mt, err, "List error: %v", err)
				for cursor.Next(context.Background()) {
					var idx index
					err = cursor.Decode(&idx)
					assert.Nil(mt, err, "Decode error: %v (document %v)", err, cursor.Current)
					assert.NotEqual(mt, test.want, idx.Name, "found index %v after dropping", test.want)
				}
				assert.Nil(mt, cursor.Err(), "cursor error: %v", cursor.Err())
			})
		}
	})
	mt.Run("drop all", func(mt *mtest.T) {
		iv := mt.Coll.Indexes()
		names, err := iv.CreateMany(context.Background(), []mongo.IndexModel{
			{
				Keys: bson.D{{"foo", -1}},
			},
			{
				Keys: bson.D{{"bar", 1}, {"baz", -1}},
			},
		})
		assert.Nil(mt, err, "CreateMany error: %v", err)
		assert.Equal(mt, 2, len(names), "expected 2 index names, got %v", len(names))
		_, err = iv.DropAll(context.Background())
		assert.Nil(mt, err, "DropAll error: %v", err)

		cursor, err := iv.List(context.Background())
		assert.Nil(mt, err, "List error: %v", err)
		for cursor.Next(context.Background()) {
			var idx index
			err = cursor.Decode(&idx)
			assert.Nil(mt, err, "Decode error: %v (document %v)", err, cursor.Current)
			assert.NotEqual(mt, names[0], idx.Name, "found index %v, after dropping", names[0])
			assert.NotEqual(mt, names[1], idx.Name, "found index %v, after dropping", names[1])
		}
		assert.Nil(mt, cursor.Err(), "cursor error: %v", cursor.Err())
	})
	mt.RunOpts("clustered indexes", mtest.NewOptions().MinServerVersion("5.3"), func(mt *mtest.T) {
		const name = "clustered"
		clustered := mt.CreateCollection(mtest.Collection{
			Name:       name,
			CreateOpts: options.CreateCollection().SetClusteredIndex(bson.D{{"key", bson.D{{"_id", 1}}}, {"unique", true}}),
		}, true)
		mt.Run("create one", func(mt *mtest.T) {
			_, err := clustered.Indexes().CreateOne(context.Background(), mongo.IndexModel{
				Keys: bson.D{{"foo", int32(-1)}},
			})
			assert.Nil(mt, err, "CreateOne error: %v", err)
			specs, err := clustered.Indexes().ListSpecifications(context.Background())
			assert.Nil(mt, err, "ListSpecifications error: %v", err)
			expectedSpecs := []*mongo.IndexSpecification{
				{
					Name:         "_id_",
					Namespace:    mt.DB.Name() + "." + name,
					KeysDocument: bson.Raw(bsoncore.NewDocumentBuilder().AppendInt32("_id", 1).Build()),
					Version:      2,
					Unique:       func(b bool) *bool { return &b }(true),
					Clustered:    func(b bool) *bool { return &b }(true),
				},
				{
					Name:         "foo_-1",
					Namespace:    mt.DB.Name() + "." + name,
					KeysDocument: bson.Raw(bsoncore.NewDocumentBuilder().AppendInt32("foo", -1).Build()),
					Version:      2,
				},
			}
			assert.True(mt, cmp.Equal(specs, expectedSpecs), "expected specifications to match: %v", cmp.Diff(specs, expectedSpecs))
		})
	})
}

func getIndexDoc(mt *mtest.T, iv mongo.IndexView, expectedKeyDoc bson.D) bson.D {
	c, err := iv.List(context.Background())
	assert.Nil(mt, err, "List error: %v", err)

	for c.Next(context.Background()) {
		var index bson.D
		err = c.Decode(&index)
		assert.Nil(mt, err, "Decode error: %v", err)

		for _, elem := range index {
			if elem.Key != "key" {
				continue
			}

			if cmp.Equal(expectedKeyDoc, elem.Value.(bson.D)) {
				return index
			}
		}
	}
	return nil
}

func checkIndexDocContains(mt *mtest.T, indexDoc bson.D, expectedElem bson.E) {
	for _, elem := range indexDoc {
		if elem.Key != expectedElem.Key {
			continue
		}

		assert.Equal(mt, expectedElem, elem, "expected element %v, got %v", expectedElem, elem)
		return
	}

	mt.Fatalf("no element matching %v found", expectedElem)
}

func verifyIndexExists(mt *mtest.T, iv mongo.IndexView, expected index) {
	mt.Helper()

	cursor, err := iv.List(context.Background())
	assert.Nil(mt, err, "List error: %v", err)

	var found bool
	for cursor.Next(context.Background()) {
		var idx index
		err = cursor.Decode(&idx)
		assert.Nil(mt, err, "Decode error: %v", err)

		if idx.Name == expected.Name {
			if expected.Key != nil {
				assert.Equal(mt, expected.Key, idx.Key, "key document mismatch; expected %v, got %v", expected.Key, idx.Key)
			}
			found = true
		}
	}
	assert.Nil(mt, cursor.Err(), "cursor error: %v", err)
	assert.True(mt, found, "expected to find index %v but was not found", expected.Name)
}