You can do it as documented at Collection.EnsureIndex
:
Other kinds of indexes are also supported through that API. Here is an example:
index := Index{
Key: []string{"$2d:loc"},
Bits: 26,
}
err := collection.EnsureIndex(index)
The example above requests the creation of a "2d" index for the "loc" field.
So basically, you have the format $<indexType>:<indexedField>
, as shown below:
package main
import mgo "gopkg.in/mgo.v2"
const (
db = "so_hashed_idx"
coll = "testcoll"
)
func main() {
var s *mgo.Session
var err error
if s, err = mgo.Dial("127.0.0.1:27017"); err != nil {
panic(err)
}
// An index spec is nothing more than a fancy word for the keys
// or the key/value pairs handed over to the Key slice of the
// Index type.
idx := mgo.Index{
Key: []string{"$hashed:_id"},
}
if err := s.DB(db).C(coll).EnsureIndex(idx); err != nil {
panic(err)
}
}
Building and running the above results in so_hashed_idx.testcoll
showing its indices as follows
> db.testcoll.getIndices()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "so_hashed_idx.testcoll"
},
{
"v" : 1,
"key" : {
"_id" : "hashed"
},
"name" : "_id_hashed",
"ns" : "so_hashed_idx.testcoll"
}
]