【问题标题】:How to fetch and inspect mongodb index options using the go mongo driver如何使用 go mongo 驱动程序获取和检查 mongodb 索引选项
【发布时间】:2021-10-03 05:23:34
【问题描述】:

我需要使用 go mongo 驱动程序 (go.mongodb.org/mongo-driver/mongo) 获取特定集合的所有索引并检查它们的索引选项

这是我正在使用的代码:

cur, err := collection.Indexes().List(ctx)
if err != nil {
   return err
}

for cur.Next(ctx) {
    index := &mongo.IndexModel{}
    if err := cur.Decode(index); err != nil {
        return fmt.Errorf("could not decode index: %w", err)
    }

   // access index.Options
   // ...
}

但是,index 变量是空的,所以我猜它无法解码为IndexModel 类型。我也没有收到错误。有人可以就如何正确地做到这一点提供建议吗?

【问题讨论】:

  • 您在文档中看到example 了吗?不是最好的例子,但总比没有好。
  • @rustyx,该示例基本上生成了bson.M 对象的切片,并且不尝试对其进行解码。 OP 示例中的调用cur.Decode() 基本上是尝试将单个这样的bson.M 对象解码为mongo.IndexModel。我的看法是 collection.Indexes().List() 迭代的不是 mongo.IndexModel 但我不知道它们是什么。我首先会尝试检查那些 bson.M 对象而不尝试对其进行解码。

标签: mongodb go mongo-go-driver


【解决方案1】:

我有一个包含mongo shell 中列出的索引的集合:

[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "test.books"
        },
        {
                "v" : 2,
                "unique" : true,
                "key" : {
                        "author" : 1,
                        "title" : 1
                },
                "name" : "author_1_title_1",
                "ns" : "test.books"
        }
]

使用 golang 列出的相同索引:

collection := client.Database("test").Collection("books")
indexView := collection.Indexes()
opts := options.ListIndexes().SetMaxTime(2 * time.Second)
cursor, err := indexView.List(context.TODO(), opts)

if err != nil {
    log.Fatal(err)
}

var result []bson.M
if err = cursor.All(context.TODO(), &result); err != nil {
    log.Fatal(err)
}

for _, v := range result {
    for k1, v1 := range v {
        fmt.Printf("%v: %v\n", k1, v1)
    }
    fmt.Println()
}

输出是:

v: 2
key: map[_id:1]
name: _id_
ns: test.books

v: 2
unique: true
key: map[author:1 title:1]
name: author_1_title_1
ns: test.books

[ EDIT ADD ] 这是略有不同的版本result 循环,map 打印为键值:

for _, v := range result {
    for k1, v1 := range v {
        if reflect.ValueOf(v1).Kind() == reflect.Map {
            v1a := v1.(primitive.M)
            fmt.Printf("%v: {\n", k1)
            for k2, v2 := range v1a {
                fmt.Printf("  %v: %v\n", k2, v2)
            }
            fmt.Printf("}\n")
        } else {
            fmt.Printf("%v: %v\n", k1, v1)
        }
    }
    fmt.Println()
}

输出:

key: {
  _id: 1
}
name: _id_
ns: test.books
v: 2

v: 2
unique: true
key: {
  title: 1
  author: 1
}
name: author_1_title_1
ns: test.books

【讨论】:

  • 谢谢,所以似乎无法将输出解码为mongo.IndexModel
猜你喜欢
  • 1970-01-01
  • 2020-04-02
  • 2020-11-17
  • 2020-08-08
  • 1970-01-01
  • 1970-01-01
  • 2019-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多