Как использовать Go с MongoDB?
MongoDB — это база данных NoSQL с открытым исходным кодом. Это документно-ориентированная база данных, использующая JSON-подобную структуру, называемую BSON, для хранения документов (т. е. пар ключ-значение). MongoDB предоставляет концепцию коллекции для группировки документов. В этой статье мы обсудим, кто связывает MongoDB с Golang.
Предварительное условие: вам необходимо установить MongoDB и запустить его на порту по умолчанию (например, 27017).
Установка: пакет mongo предоставляет API драйвера MongoDB для Go, который можно использовать для взаимодействия с API MongoDB. Используйте приведенную ниже команду для установки пакета mongo.
go get go.mongodb.org/mongo-driver/mongo
Контекст пакета: Контекст пакета — это тип контекста, который содержит крайние сроки, сигналы отмены и другие значения в области запроса через границы API и между процессами.
Подключить драйвер Go к MongoDB
Теперь, чтобы подключить драйвер Go к MongoDB, вам необходимо выполнить следующие шаги:
- Создайте mongo.Client с функцией mongo.Connect. mongo.Client обрабатывает соединение с MongoDB.
- mongo.Client имеет метод Ping, который возвращает pong при успешном соединении.
- Наконец, используйте mongo.Client.Disconnect, чтобы закрыть соединение с базой данных.
Go
package mainimport ( "context" "fmt" "time" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref")// This is a user defined method to close resources.// This method closes mongoDB connection and cancel context.func close(client *mongo.Client, ctx context.Context, cancel context.CancelFunc){ // CancelFunc to cancel to context defer cancel() // client provides a method to close // a mongoDB connection. defer func(){ // client.Disconnect method also has deadline. // returns error if any, if err := client.Disconnect(ctx); err != nil{ panic(err) } }()}// This is a user defined method that returns mongo.Client,// context.Context, context.CancelFunc and error.// mongo.Client will be used for further database operation.// context.Context will be used set deadlines for process.// context.CancelFunc will be used to cancel context and// resource associated with it.func connect(uri string)(*mongo.Client, context.Context, context.CancelFunc, error) { // ctx will be used to set deadline for process, here // deadline will of 30 seconds. ctx, cancel := context.WithTimeout(context.Background(), 30 * time.Second) // mongo.Connect return mongo.Client method client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri)) return client, ctx, cancel, err}// This is a user defined method that accepts// mongo.Client and context.Context// This method used to ping the mongoDB, return error if any.func ping(client *mongo.Client, ctx context.Context) error{ // mongo.Client has Ping to ping mongoDB, deadline of // the Ping method will be determined by cxt // Ping method return error if any occurred, then // the error can be handled. if err := client.Ping(ctx, readpref.Primary()); err != nil { return err } fmt.Println("connected successfully") return nil}func main(){ // Get Client, Context, CancelFunc and // err from connect method. if err != nil { panic(err) } // Release resource when the main // function is returned. defer close(client, ctx, cancel) // Ping mongoDB with Ping method ping(client, ctx)} |
Выход:

Вставка документов
Для вставки документов необходимо выполнить следующие шаги:
- Создайте mongo.Client с функцией mongo.Connect. mongo.Client обрабатывает соединение с MongoDB.
- mongo.Client.Database возвращает тип указателя на базу данных.
- Указатель на базу данных имеет коллекцию методов для выбора коллекции для работы.
- Тип коллекции предоставляет два метода для вставки документа в MongoDB.
- Метод Collection.InsertOne() может вставить один документ в базу данных.
- Метод Collection.InsertMany() может вставлять список документов.
- Затем, наконец, используйте mongo.Client.Disconnect, чтобы закрыть соединение с базой данных.
Выход:
Поиск документов
Для поиска документов необходимо выполнить следующие действия:
- Создайте mongo.Client с функцией mongo.Connect. mongo.Client обрабатывает соединение с MongoDB.
- mongo.Client.Database возвращает тип указателя на базу данных.
- Указатель на базу данных имеет коллекцию методов для выбора коллекции для работы.
- Коллекция предоставляет метод Find() для запроса к базе данных.
- Затем, наконец, используйте mongo.Client.Disconnect, чтобы закрыть соединение с базой данных.
Go
package mainimport ( "context" "fmt" "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref")// This is a user defined method to close resources.// This method closes mongoDB connection and cancel context.func close(client *mongo.Client, ctx context.Context, cancel context.CancelFunc) { defer cancel() defer func() { if err := client.Disconnect(ctx); err != nil { panic(err) } }()}// This is a user defined method that returns// a mongo.Client, context.Context,// context.CancelFunc and error.// mongo.Client will be used for further database// operation. context.Context will be used set// deadlines for process. context.CancelFunc will// be used to cancel context and resource// associated with it.func connect(uri string) (*mongo.Client, context.Context, context.CancelFunc, error) { ctx, cancel := context.WithTimeout(context.Background(), 30 * time.Second) client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri)) return client, ctx, cancel, err}// query is user defined method used to query MongoDB,// that accepts mongo.client,context, database name,// collection name, a query and field.// database name and collection name is of type// string. query is of type interface.// field is of type interface, which limits// the field being returned.// query method returns a cursor and error.func query(client *mongo.Client, ctx context.Context,dataBase, col string, query, field interface{})(result *mongo.Cursor, err error) { // select database and collection. collection := client.Database(dataBase).Collection(col) // collection has an method Find, // that returns a mongo.cursor // based on query and field. result, err = collection.Find(ctx, query, options.Find().SetProjection(field)) return}func main() { // Get Client, Context, CancelFunc and err from connect method. if err != nil { panic(err) } // Free the resource when main function is returned defer close(client, ctx, cancel) // create a filter an option of type interface, // that stores bjson objects. var filter, option interface{} // filter gets all document, // with maths field greater that 70 filter = bson.D{ {"maths", bson.D{{"$gt", 70}}}, } // option remove id field from all documents option = bson.D{{"_id", 0}} // call the query method with client, context, // database name, collection name, filter and option // This method returns momngo.cursor and error if any. cursor, err := query(client, ctx, "gfg", "marks", filter, option) // handle the errors. if err != nil { panic(err) } var results []bson.D // to get bson object from cursor, // returns error if any. if err := cursor.All(ctx, &results); err != nil { // handle the error panic(err) } // printing the result of query. fmt.Println("Query Result") for _, doc := range results { fmt.Println(doc) }} |
Выход:
Обновление документа
Для обновления документов необходимо выполнить следующие действия:
- Создайте mongo.Client с функцией mongo.Connect. mongo.Client обрабатывает соединение с MongoDB.
- mongo.Client.Database возвращает тип указателя на базу данных.
- Указатель на базу данных имеет коллекцию методов для выбора коллекции для работы.
- Коллекция предоставляет два метода обновления документов.
- Метод UpdateOne() изменяет один документ, соответствующий запросу
- Метод UpdateMany() изменяет каждый документ, соответствующий запросу.
- Затем, наконец, используйте mongo.Client.Disconnect, чтобы закрыть соединение с базой данных.
Go
package mainimport ( "context" "fmt" "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref")// This is a user defined method to close resources.// This method closes mongoDB connection and cancel context.func close(client *mongo.Client, ctx context.Context, cancel context.CancelFunc) { defer cancel() defer func() { if err := client.Disconnect(ctx); err != nil { panic(err) } }()}// This is a user defined method that returns// mongo.Client, context.Context,// context.CancelFunc and error.// mongo.Client will be used for further database// operation.context.Context will be used set// deadlines for process. context.CancelFunc will// be used to cancel context and resource// associated with it.func connect(uri string)(*mongo.Client, context.Context, context.CancelFunc, error) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri)) return client, ctx, cancel, err}// UpdateOne is a user defined method, that update// a single document matching the filter.// This methods accepts client, context, database,// collection, filter and update filter and update// is of type interface this method returns// UpdateResult and an error if any.func UpdateOne(client *mongo.Client, ctx context.Context, dataBase, col string, filter, update interface{}) (result *mongo.UpdateResult, err error) { // select the database and the collection collection := client.Database(dataBase).Collection(col) // A single document that match with the // filter will get updated. // update contains the filed which should get updated. result, err = collection.UpdateOne(ctx, filter, update) return}// UpdateMany is a user defined method, that update// a multiple document matching the filter.// This methods accepts client, context, database,// collection, filter and update filter and update// is of type interface this method returns// UpdateResult and an error if any.func UpdateMany(client *mongo.Client, ctx context.Context, dataBase, col string, filter, update interface{}) (result *mongo.UpdateResult, err error) { // select the database and the collection collection := client.Database(dataBase).Collection(col) // All the documents that match with the filter will // get updated. // update contains the filed which should get updated. result, err = collection.UpdateMany(ctx, filter, update) return}func main() { // get Client, Context, CancelFunc and err from connect method. if err != nil { panic(err) } // Free the resource when main function in returned defer close(client, ctx, cancel) // filter object is used to select a single // document matching that matches. filter := bson.D{ {"maths", bson.D{{"$lt", 100}}}, } // The field of the document that need to updated. update := bson.D{ {"$set", bson.D{ {"maths", 100}, }}, } // Returns result of updated document and a error. result, err := UpdateOne(client, ctx, "gfg", "marks", filter, update) // handle error if err != nil { panic(err) } // print count of documents that affected fmt.Println("update single document") fmt.Println(result.ModifiedCount) filter = bson.D{ {"computer", bson.D{{"$lt", 100}}}, } update = bson.D{ {"$set", bson.D{ {"computer", 100}, }}, } // Returns result of updated document and a error. result, err = Update(client, ctx, "gfg", "marks", filter, update) // handle error if err != nil { panic(err) } // print count of documents that affected fmt.Println("update multiple document") fmt.Println(result.ModifiedCount)} |
Выход:
Удаление документов
Для удаления документов необходимо выполнить следующие действия:
- Создайте mongo.Client с функцией mongo.Connect. mongo.Client обрабатывает соединение с MongoDB.
- mongo.Client.Database возвращает тип указателя на базу данных.
- Указатель на базу данных имеет коллекцию методов для выбора коллекции для работы.
- Коллекция предоставляет два метода для удаления документов в коллекции.
- Функция DeleteOne() удаляет один документ, соответствующий запросу.
- Функция DeleteMany() удаляет все документы, соответствующие запросу.
- Затем, наконец, используйте mongo.Client.Disconnect, чтобы закрыть соединение с базой данных.