这些方法是否在MongoDB服务器中创建新的数据库和集合

From Web Development with Go by Shiju Varghese

To perform CRUD operations into MongoDB, an object of *mgo.Collection is created, which represents the MongoDB collection. You can create an object of *mgo.Collection by calling method C of *mgo.Database.

The mgo.Database type represents the named database that can be created by calling the DB method of *mgo.Session.

Listing 8-5 accesses the MongoDB collection named "categories".

Listing 8-5. Accessing a MongoDB Collection

c := session.DB("taskdb").C("categories")

Do the DB and C methods create database object and collection object in Go programs both

  • for existing database and existing collection in a MongoDB server?

  • for noexisting database and nonexisting collection, so that the methods will create new database and collection in a MongoDB server, which will be named as the arguments to the methods?

Thanks.

In MongoDB, a new DB and collection will be created only after a write operation, after inserting first document in a specific database and collection.

In MongoDB there is no CREATE TABLE like command/function, no need for that.

Your code does not create a collection since is not inserting new documents in new collection. In your code you don't need to worry about creating dbs or collections