mongodb - 如何通过 mgo (golang) 创建哈希索引

标签 mongodb go mgo

如何使用 mgo 创建(或确保)散列索引包?

我需要一个与此等效的 go 代码:

>> db.collection.createIndex( { _id: "hashed" } )

我尝试过使用 runCommand,但只有 ‍createIndexes 命令需要索引规范列表。我不知道那是什么以及如何创建索引规范

最佳答案

您可以按照 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.

基本上,您的格式为 $<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"
    }
]

关于mongodb - 如何通过 mgo (golang) 创建哈希索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45389410/

相关文章:

linux - 将 mongo 2.4 更新到 2.6

regex - 在golang中用零替换数字

go - 用于寻路的 mgo 优化

mongodb - 具有嵌套嵌入文档和 $project 的 Mongo 聚合管道 $lookup

mongodb - 使用 Paypal REST api 获取计费协议(protocol)列表

node.js - Mongoose 在未指定的时间段后停止响应

javascript - Mongoose .findOne 错误返回找到的模型?

go - 从Go程序访问AKS kubeconfig文件

opengl - Go go-gl OpenGL 渲染问题

json - 我可以在 mgo 中使用 json 标签作为 bson 标签吗?