如何使用Go Mongo驱动程序获取和检查MongoDB索引选项?

huangapple go评论82阅读模式
英文:

How to fetch and inspect mongodb index options using the go mongo driver

问题

我需要使用Go MongoDB驱动程序(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("无法解码索引:%w", err)
	}

   // 访问 index.Options
   // ...
}

然而,index 变量是空的,所以我猜它无法解码为 IndexModel 类型。我也没有收到错误。有人可以给出如何正确执行的建议吗?

英文:

I need to get all indexes of a specific collection and inspect their index options using the go mongo driver (go.mongodb.org/mongo-driver/mongo)

Here is the code I am using:

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
   // ...
}

However, the index variable is empty, so I guess it could not be decoded into the IndexModel type. I don't get an error either. Can somebody give advice on how to do it correctly?

答案1

得分: 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

[编辑添加] 这是稍微不同版本的 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
英文:

I have a collection with indexes as listed in 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"
        }
]

The same indexes listed using 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()
}

The output is:

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

<hr>

[ EDIT ADD ] This is slightly different version result loop with map printed as key-values:

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

The output:

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

答案2

得分: 0

驱动程序还公开了ListSpecifications方法。它返回具有索引信息的IndexSpecification

collection.Indexes().ListSpecifications(ctx)
英文:

The driver also exposes ListSpecifications method. It returns the IndexSpecification with index information.

collection.Indexes().ListSpecifications(ctx)

huangapple
  • 本文由 发表于 2021年7月27日 19:23:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/68543962.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定