Skip to main content

mongo Database Operations


Create a valid monodb database connection via monodb uri.


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

Function signature: 
MustaNewModel function (uri, db, collection string, opts, ..Option) *Model
1. Exit log out directly when monodb links create problems.
2. Create db and collection when db and collection do not exist.
1. uri: mongodb uri (example: monodb:/<user>:<password>@<host>:<port>)
2. db: Database name
3. collection: collection name
return value:
1. *Model: Connection management object

2 NewModel

Function signature: 
NewModel func(uri, db, collection string, opts ..Option) (*Model, error)
1. When db and collection do not exist, db and collection will be created.
1. uri: monodb uri (example: mongodb://<user>:<password>@<host>:<port>)
db: Database name
3. collection: collection name
Return value:
1. *Model: Connect to manage object
2. error: Create error

Code Example

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