1、拉去docker镜像:
docker pull mongo
2、启动容器
docker run -itd --name mymongo -p 27017:27017 mongo --auth
3、进入到容器中
docker exec -it mymongo mongo admin
4、创建一个mongo的用户(用户名,密码自己设置)
db.createUser({ user:'admin',pwd:'123456',roles:[ { role:'userAdminAnyDatabase', db: 'admin'},"readWriteAnyDatabase"]});
5、测试:使用刚刚创建的用户登陆
db.auth('admin', '123456')
6、使用程序链接mongo(我是使用go,其他语言去找一下相对应地第三方包,大体意思相近)
package main
import (
"context"
"fmt"
"net/url"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type MongoConf struct {
Host string `toml:"host"`
Port int `toml:"port"`
Database string `toml:"database"`
Username string `toml:"username"`
Password string `toml:"password"`
MaxPoolSize uint64 `toml:"maxPoolSize"`
MinPoolSize uint64 `toml:"minPoolSize"`
ConnectTimeout int `toml:"connectTimeout"`
}
var database *mongo.Database
func Instance() *mongo.Database {
return database
}
func main() {
t := MongoConf{
Host: "127.0.0.1",
Port: 27017,
Database:"demo",
Username:"admin",
Password: "123456",
MaxPoolSize: 100,
MinPoolSize: 20,
ConnectTimeout: 100,
}
_, err := New(&t)
fmt.Println("==>>",err)
if err == nil{
err := Create(context.TODO(), &t)
fmt.Println("creat err:",err)
}
}
func New(conf *MongoConf) (client *mongo.Client, err error) {
DSN := fmt.Sprintf("mongodb://%s:%s@%s:%d/%s?authSource=admin", conf.Username, url.PathEscape(conf.Password), conf.Host, conf.Port, conf.Database)
option := options.Client().ApplyURI(DSN)
option.SetMaxPoolSize(conf.MaxPoolSize)
option.SetMinPoolSize(conf.MinPoolSize)
option.SetConnectTimeout(time.Duration(conf.ConnectTimeout) * time.Millisecond)
if client, err = mongo.NewClient(option); err != nil {
return
}
if err = client.Connect(context.TODO()); err != nil {
return
}
if err = client.Ping(context.TODO(), nil); err != nil {
return
}
database = client.Database(conf.Database)
return client, nil
}
func Create(ctx context.Context, doc *MongoConf) (err error) {
collection := database.Collection("hello")
if _, err = collection.InsertOne(ctx, doc); err != nil {
fmt.Println(err)
return
}
return
}