mongodb golang check collection exists

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

mongodb golang check collection exists

问题

我需要检查一个集合是否存在。

我创建了以下函数:

func ExitsCollection(name string) bool {

	var exists bool = false

	names, err := cliente.CollectionNames()
	if err != nil {
		log.Println("[-]无法检索集合列表")
	}

	// 在names中查找
	for _, name := range names {
		if name == name {
			log.Printf("[+]集合已存在!")
			exists = true
			break
		}
	}

	if !exists {
		log.Println("[+]集合不存在")
	}

	return exists
}

为了连接,我使用了下面的函数:

func ConectaBD() {

	cliente_local, err := mongo.NewClient(options.Client().ApplyURI(cadena_conexion))
	if err != nil {
		log.Fatal(err)
	}

	ctx, cancelar = context.WithTimeout(context.Background(), 10*time.Second)
	err = cliente_local.Connect(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer cancelar()

	mongo_cliente = cliente_local.Database(DATABASE)

	log.Println("[+]连接到MongoDB Atlas")

}

我使用了以下变量:

var cliente_local *mongo.Client
var mongo_cliente *mongo.Database
var coleccion *mongo.Collection
var ctx context.Context
var cancelar context.CancelFunc

问题是下面这句话:

names, err := cliente.CollectionNames()

这个方法返回什么类型的数据?我该如何使用CollectionNames()方法?

有人有示例源代码吗?

提前感谢大家的帮助!

===========================================

谢谢大家的帮助!我已经为会话管理创建了另一个问题:

https://stackoverflow.com/questions/70505598/how-i-get-a-session-in-mongodb-with-golang

英文:

I need to check if a collection exists.

I have created the following function:

func ExitsCollection(name string) bool {

	var exists bool = false

	names, err := cliente.CollectionNames()
	if err != nil {
		log.Println("[-]I cannot retrieve the list of collections")
	}

	// Simply search in the names
	for _, name := range names {
		if name == name {
			log.Printf("[+]The collection already exists!")
			exists = true
			break
		}
	}

	if !exists {
		log.Println("[+] The collection does not exist")
	}

	return exists
}

In order to connect I use the next function:

func ConectaBD() {

	cliente_local, err := mongo.NewClient(options.Client().ApplyURI(cadena_conexion))
	if err != nil {
		log.Fatal(err)
	}

	ctx, cancelar = context.WithTimeout(context.Background(), 10*time.Second)
	err = cliente_local.Connect(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer cancelar()

	mongo_cliente = cliente_local.Database(DATABASE)

	log.Println("[+]Connected to MongoDB Atlas")

}

I use the following variables:

var cliente_local *mongo.Client
var mongo_cliente *mongo.Database
var coleccion *mongo.Collection
var ctx context.Context
var cancelar context.CancelFunc

The problem is the next sentence:

names, err := cliente.CollectionNames()

What type of data or How do I can use the method CollectionNames()?

Does anyone have a sample source code?

Thanks in advance

===========================================

thank you all for your help!!!
I have created another question for session management:

https://stackoverflow.com/questions/70505598/how-i-get-a-session-in-mongodb-with-golang

答案1

得分: 1

Database.CollectionNames() 返回数据库中存在的集合名称。返回类型是 slice,因此您需要检查您的集合是否在列表中。

请查看官方文档:https://pkg.go.dev/gopkg.in/mgo.v2#Database.CollectionNames

sess := ... // 获取会话
db := sess.DB("") // 获取数据库,如果连接URL中未提供数据库名称,则使用数据库名称

names, err := db.CollectionNames()
if err != nil {
    // 处理错误
    log.Printf("获取集合名称失败:%v", err)
    return
}

// 在 names 切片中进行搜索,例如
for _, name := range names {
    if name == "collectionToCheck" {
        log.Printf("集合存在!")
        break
    }
}

为了更好地理解,请参考此链接:https://stackoverflow.com/questions/46293070/how-to-check-if-collection-exists-or-not-mongodb-golang

英文:

Database.CollectionNames() returns the collection names present in the db database. The return type is slice so you need to check if your collection is listed or not.

Please check the official docs : https://pkg.go.dev/gopkg.in/mgo.v2#Database.CollectionNames

sess := ... // obtain session
db := sess.DB("") // Get db, use db name if not given in connection url

names, err := db.CollectionNames()
if err != nil {
    // Handle error
    log.Printf("Failed to get coll names: %v", err)
    return
}

// Simply search in the names slice, e.g.
for _, name := range names {
    if name == "collectionToCheck" {
        log.Printf("The collection exists!")
        break
    }
}

For better understanding refer this link : https://stackoverflow.com/questions/46293070/how-to-check-if-collection-exists-or-not-mongodb-golang

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

发表评论

匿名网友

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

确定