From 8aa53c0f08d3dce6a8a44d1be6ad0bff8b3f33f4 Mon Sep 17 00:00:00 2001 From: Jens Teichert Date: Sun, 24 Mar 2024 13:10:06 +0100 Subject: [PATCH] add support for multi key indices --- indexes.go | 5 +++-- indexes_test.go | 30 +++++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/indexes.go b/indexes.go index 0a8ee94..2c46c1c 100644 --- a/indexes.go +++ b/indexes.go @@ -5,9 +5,10 @@ import ( "go.mongodb.org/mongo-driver/mongo" ) -func (repo *Collection[T]) CreateIndex(keys bson.M) error { +func (repo *Collection[T]) CreateIndex(keys bson.D) error { mod := mongo.IndexModel{ - Keys: keys, Options: nil, + Keys: keys, + Options: nil, } _, err := repo.collection.Indexes().CreateOne(DefaultContext(), mod) diff --git a/indexes_test.go b/indexes_test.go index 3c30a9a..f3ab3d9 100644 --- a/indexes_test.go +++ b/indexes_test.go @@ -21,7 +21,35 @@ func TestCollection_CreateIndex(t *testing.T) { indexCountBefore := len(indxs) - err := collection.CreateIndex(bson.M{fmt.Sprint(rand.Int()): 1}) + err := collection.CreateIndex(bson.D{ + {fmt.Sprint(rand.Int()), 1}, + }) + + assert.Nil(t, err) + + indexCursor2, _ := collection.collection.Indexes().List(DefaultContext()) + indexCursor2.All(DefaultContext(), &indxs) + + // new index + assert.Equal(t, len(indxs), indexCountBefore+1) +} + +func TestCollection_CreateMultiKeyIndex(t *testing.T) { + rand.Seed(time.Now().UnixNano()) + mockDb.Connect("mongodb://localhost:27017/colt?readPreference=primary&directConnection=true&ssl=false", "colt") + + collection := GetCollection[*testdoc](&mockDb, "testdocs") + + var indxs = []interface{}{} + indexCursor, _ := collection.collection.Indexes().List(DefaultContext()) + indexCursor.All(DefaultContext(), &indxs) + + indexCountBefore := len(indxs) + + err := collection.CreateIndex(bson.D{ + {fmt.Sprint(rand.Int()), 1}, + {fmt.Sprint(rand.Int()), 1}, + }) assert.Nil(t, err)