如何在MongoDB中列出集合?

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

How to list collections in mongodb

问题

在golang中,我可以获取以下mongodb数据库名称的列表:

  1. filter := bson.D{{}}
  2. dbs, _ := client.ListDatabaseNames(context.TODO(), filter)
  3. fmt.Printf("%+v\n", dbs)

但是,我想获取集合名称的列表。

英文:

In golang..
I get list mongodb database name below..

  1. filter := bson.D{{}}
  2. dbs, _ := client.ListDatabaseNames(context.TODO(), filter)
  3. fmt.Printf("%+v\n", dbs)

But, I want to get list collections name.

答案1

得分: 5

ListCollectionNames怎么样?

这是文档中的一个示例。我添加了一些占位行,你需要用你的客户端连接代码和获取数据库的代码替换它们:

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "go.mongodb.org/mongo-driver/bson"
  7. "go.mongodb.org/mongo-driver/mongo"
  8. )
  9. func main() {
  10. // 占位符:
  11. //
  12. // 连接到MongoDB,处理错误
  13. client, err := mongo.Connect(....)
  14. if err != nil {
  15. log.Fatal(err)
  16. }
  17. // 通过名称获取数据库。db的类型将是*mongo.Database
  18. db := client.Database("你的数据库名称")
  19. // 使用过滤器仅选择有限集合
  20. result, err := db.ListCollectionNames(
  21. context.TODO(),
  22. bson.D{{"options.capped", true}})
  23. if err != nil {
  24. log.Fatal(err)
  25. }
  26. for _, coll := range result {
  27. fmt.Println(coll)
  28. }
  29. }
英文:

How about ListCollectionNames?

Here's an example from the documentation. I added some placeholder lines that you need to replace by your client connection code and getting a database:

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "go.mongodb.org/mongo-driver/bson"
  7. "go.mongodb.org/mongo-driver/mongo"
  8. )
  9. func main() {
  10. // Placeholder:
  11. //
  12. // Connect to MongoDB, handle error
  13. client, err := mongo.connect(....)
  14. if err != nil {
  15. log.Fatal(err)
  16. }
  17. // Obtain the DB, by name. db will have the type
  18. // *mongo.Database
  19. db := client.Database("name-of-your-DB")
  20. // use a filter to only select capped collections
  21. result, err := db.ListCollectionNames(
  22. context.TODO(),
  23. bson.D{{"options.capped", true}})
  24. if err != nil {
  25. log.Fatal(err)
  26. }
  27. for _, coll := range result {
  28. fmt.Println(coll)
  29. }
  30. }

huangapple
  • 本文由 发表于 2021年6月9日 11:26:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/67897120.html
匿名

发表评论

匿名网友

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

确定