mongo Database Operations

Overview

Create a valid monodb database connection via monodb uri.

Preparing

  1. Complete golang installation
  2. Create a mono server on our own and we use mongodb/admin:123456@localhost as an example

Toolkit Description

go-zero contains two mongodb toolkits, mono are deprecated, no longer supports maintenance, and mon is recommended.

All presentations for this section are based on mon toolkits.

We also recommend using byctl to generate mono models for business development.

Create Database Connection

Database connection creation provides two methods,MostNewModel and NewModel.

Methodological description

  1. MustNewModel
  1. Function signature:
  2. MustaNewModel function (uri, db, collection string, opts, ..Option) *Model
  3. description:
  4. 1. Exit log out directly when monodb links create problems.
  5. 2. Create db and collection when db and collection do not exist.
  6. Input:
  7. 1. uri: mongodb uri (example: monodb:/<user>:<password>@<host>:<port>)
  8. 2. db: Database name
  9. 3. collection: collection name
  10. return value:
  11. 1. *Model: Connection management object
  1. NewModel
  1. Function signature:
  2. NewModel func(uri, db, collection string, opts ..Option) (*Model, error)
  3. description:
  4. 1. When db and collection do not exist, db and collection will be created.
  5. Input:
  6. 1. uri: monodb uri (example: mongodb://<user>:<password>@<host>:<port>)
  7. db: Database name
  8. 3. collection: collection name
  9. Return value:
  10. 1. *Model: Connect to manage object
  11. 2. error: Create error

Code Example

  1. conn := mon.MustNewModel("mongodb://<user>:<password>@<host>:<port>", "db", "collection")

References