【问题标题】:mongodb golang check collection exists [closed]mongodb golang检查集合存在[关闭]
【发布时间】:2022-01-26 08:52:03
【问题描述】:

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

我创建了以下函数:

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
}

为了连接,我使用了下一个函数:

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")

}

我使用以下变量:

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

问题是下一句:

名称,错误 := cliente.CollectionNames()

什么类型的数据或如何使用方法 CollectionNames()?

有人有示例源代码吗?

提前致谢

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

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

how i get a session in mongodb with golang

【问题讨论】:

  • if name == name - 这永远是真的
  • "什么类型的数据或如何使用 CollectionNames() 方法?" - 文档说明了这个方法返回什么?
  • func (db *Database) CollectionNames() (names []string, err error) 存储库:github.com/go-mgo/mgo
  • 不过,您没有使用 mgo。 (从你对mongo.Clientmongo.Database等的使用来看)
  • RE:“问题是下一句话:”究竟是什么问题?如果它是一个错误,它应该被逐字包含在问题中。请阅读有关询问的帮助中心文档,尤其是how to ask good questions

标签: mongodb go


【解决方案1】:

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

请查看官方文档: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
    }
}

为了更好地理解,请参阅此链接:How to check if collection exists or not MongoDB Golang

【讨论】:

猜你喜欢
  • 2018-02-27
  • 2020-08-31
  • 2015-11-01
  • 2014-06-30
  • 2018-08-11
  • 1970-01-01
  • 2016-08-17
  • 1970-01-01
  • 2017-09-15
相关资源
最近更新 更多