Skip to content

Commit

Permalink
add support for multi key indices
Browse files Browse the repository at this point in the history
  • Loading branch information
jensteichert committed Mar 24, 2024
1 parent ceb535d commit 8aa53c0
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
5 changes: 3 additions & 2 deletions indexes.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
30 changes: 29 additions & 1 deletion indexes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down

0 comments on commit 8aa53c0

Please sign in to comment.