如何在MongoDB中列出集合?

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

How to list collections in mongodb

问题

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

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

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

英文:

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

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

But, I want to get list collections name.

答案1

得分: 5

ListCollectionNames怎么样?

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

package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

func main() {
    // 占位符:
    //
    // 连接到MongoDB,处理错误
    client, err := mongo.Connect(....)
    if err != nil {
        log.Fatal(err)
    }
    // 通过名称获取数据库。db的类型将是*mongo.Database
    db := client.Database("你的数据库名称")
    
	// 使用过滤器仅选择有限集合
	result, err := db.ListCollectionNames(
        context.TODO(),
        bson.D{{"options.capped", true}})

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

	for _, coll := range result {
		fmt.Println(coll)
	}
}
英文:

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:

package main

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

func main() {
    // Placeholder:
    //
    // Connect to MongoDB, handle error
    client, err := mongo.connect(....)
    if err != nil {
        log.Fatal(err)
    }
    // Obtain the DB, by name. db will have the type
    // *mongo.Database
    db := client.Database("name-of-your-DB")
    
	// use a filter to only select capped collections
	result, err := db.ListCollectionNames(
        context.TODO(),
        bson.D{{"options.capped", true}})

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

	for _, coll := range result {
		fmt.Println(coll)
	}
}

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:

确定