0

我需要获取特定集合的所有索引并使用 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类型。我也没有收到错误。有人可以就如何正确地做到这一点提供建议吗?

4

1 回答 1

0

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

[ 编辑添加 ] 这是略有不同的版本result循环,地图打印为键值:

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
于 2021-07-27T14:02:11.100 回答