您可以按照Collection.EnsureIndex 中的说明进行操作:
该 API 还支持其他类型的索引。这是一个例子:
index := Index{
Key: []string{"$2d:loc"},
Bits: 26,
}
err := collection.EnsureIndex(index)
上面的例子请求为“loc”字段创建一个“2d”索引。
所以基本上,你的格式是$<indexType>:<indexedField>,如下所示:
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)
}
}
在so_hashed_idx.testcoll 中构建并运行上述结果,显示其索引如下
> 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"
}
]