How should one work with indices?

I can find some examples for creating indices:

But listing them is where things are falling down for me. I can’t seem to find an example of List being used online.

The mongo-go-driver docs just reference the underlying command being used:

// List executes a listIndexes command and returns a cursor over the indexes in the collection.
//
// The opts parameter can be used to specify options for this operation (see the options.ListIndexesOptions
// documentation).
//
// For more information about the command, see https://docs.mongodb.com/manual/reference/command/listIndexes/.

cursor, err := coll.Indexes().List(context.Background()) returns a cursor that I can call .All() on and provide it an interface.

Unfortunately, unpacking into []mongo.IndexModel{} doesn’t seem to work. @Divjot_Arora - would you happen to have a code snippet for listing indices?

Current code:

	cursor, err := coll.Indexes().List(nil)
	is.NoError(err)
	indices := []mongo.IndexModel{}
	is.NoError(cursor.All(nil, &indices))
	is.GreaterOrEqual(len(indices), 9)

Hi @TopherGopher,

Sorry, this got lost in my inbox. mongo.IndexModel is a helper type used to store information when creating indices, not a type to unpack index specifications into. Driver version 1.5.0 will include an IndexView.ListSpecifications function that calls listIndexes and unpacks all results into a helper type rather than simply returning a Cursor object. In the meantime, you can see the struct definition for this type and copy it into your code:

type IndexSpecification struct {
// copied from Go Driver
}

cursor, err := coll.Indexes().List(nil)
is.NoError(err)
var indices []IndexSpecification
is.NoError(cursor.All(nil, &indices))
is.GreaterOrEqual(len(indicies), 9)
2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.