How to create/drop mongoDB database and collections from a golang (go language) program.?

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

How to create/drop mongoDB database and collections from a golang (go language) program.?

问题

func DatabaseConnect() (db *mongo.Database, err error) {
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		return
	}
	db = client.Database("students")
	return
}

上述函数用于连接到已经存在于MongoDB服务器上的数据库。但是我们能否编写一个类似于这个函数的函数,用于创建/删除数据库和一些集合。

func HandleDatabases(){
// 用于删除/创建/管理MongoDB数据库和集合的函数
}
英文:
func DatabaseConnect() (db *mongo.Database, err error) {
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		return
	}
	db = client.Database("students")
	return
}

this above function connects to a database which is already present on mongoDB server. But can we write a function silimar to this one, which will create/drop a database and some collections also.

func HandleDatabases(){
// for deleting / creating / managing mongoDB databases and collections ?
}

答案1

得分: 2

使用MongoDB时,数据库和集合在使用之前不需要存在。

您可以对不存在的数据库和集合运行查询,这不会导致错误,但显然不会返回任何文档。当向不存在的数据库和/或集合插入文档时,数据库和/或集合将自动创建。

要删除数据库,只需使用Database.Drop()方法。要删除集合,只需使用Collection.Drop()方法。

只有在希望创建具有非默认特殊属性的集合时,才需要在使用之前创建集合。为此,您可以使用Database.CreateCollection()

要查找服务器上已存在的数据库,可以使用Client.ListDatabases()Client.ListDatabaseNames()方法。

要查找数据库中已存在的集合,可以使用Database.ListCollections()Database.ListCollectionNames()方法。

英文:

Using MongoDB, databases and collections do not need to exist prior to using them.

You can run queries against non-existing databases and collections, which will not result in an error, but obviously won't return any documents. When inserting documents into a non-existing database and/or collection, the database and/or collection will be created automatically.

To drop a database, simply use the Database.Drop() method. To drop a collection, simply use the Collection.Drop() method.

You only need to create a collection before using it if you want it to create with non-default, special properties. For that, you may use Database.CreateCollection().

To find out which databases exist already on the server, you may use the Client.ListDatabases() or Client.ListDatabaseNames() methods.

To find out which collections exist already in a database, you may use the Database.ListCollections() or Database.ListCollectionNames() methods.

huangapple
  • 本文由 发表于 2022年1月29日 18:54:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/70904594.html
匿名

发表评论

匿名网友

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

确定