欢迎光临散文网 会员登陆 & 注册

新手使用mongodb

2023-04-15 19:24 作者:EdgeCross  | 我要投稿

# mongo

mongo适用于大数据量,高并发,轻量事物型系统

## devops

### 创建管理员账户

1. 以非授权模式启动mongod

```sh

mongod --dbpath /usr/local/var/mongodb --logpath /usr/local/var/log/mongodb/mongo.log --fork

```

2. 创建管理用户admin

`使用mongosh连接进去`

```bash

test> use admin

switched to db admin

admin> db.createUser({

...     user:"admin",

...     pwd:"admin123456",

...     roles:[{role:"userAdminAnyDatabase",db:"admin"}]

... });

{ ok: 1 }


#查看用户,另外还可以使用db.system.users.find()

admin> show users

[

{

_id: 'admin.admin',

userId: UUID("554560b1-e47b-44d9-8d3a-5f7ae5c933eb"),

user: 'admin',

db: 'admin',

roles: [ { role: 'userAdminAnyDatabase', db: 'admin' } ],

mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]

}

]

#退出来

admin> quit

```

3. 停止数据库

```sh

killall `pidof mongod`

```

### 创建业务账户

1. 以授权模式启动

```bash

```sh

mongod --auth --dbpath /usr/local/var/mongodb --logpath /usr/local/var/log/mongodb/mongo.log --fork

```

```

2. 使用admin登录

```sh

# 可直接使用mongosh进去后使用db.auth('admin','admin123456')再认证

mongosh -u admin -p

```

3. 创建业务用户

```sh

test> use biz

biz> db.createUser({user:"webopr",pwd:"123456",roles:[{role:"readWrite",db:"biz"}]})

{ ok: 1 }

```

4. 使用webopr登录

```sh

test> use biz

switched to db biz

biz> db.auth('webopr','123456')

{ ok: 1 }

biz>

biz> show tables;


# 插入数据

biz> db.users.insertOne({uid:0,age:19,name:"EdgeCross",uin:"skyhawk"})

{

acknowledged: true,

insertedId: ObjectId("6438fa7dda4faacf8d683e85")

}

# 查询刚插入的数据

biz> db.users.find();

[

{

_id: ObjectId("6438fa7dda4faacf8d683e85"),

uid: 0,

age: 19,

name: 'EdgeCross',

uin: 'skyhawk'

}

]

```

## 客户端编码

### options包

在options包, 可用来设置客户端选项(ClientOptions)。

```go

// 新建客户端选项

func Client()*ClientOptions


// 连接字符串,DSN

func (c *ClientOptions) GetURI() string

func (c *ClientOptions) ApplyURI(uri string) *ClientOptions

// 参数设置... 一些参数可通过uri参数设置

```


#### 连接字符串

```go

"mongodb://user:password@host:port/db?param1=value1&param2=value2"

```


### mongo包

#### Client

一个Client对象是一个连接池,它是并发安全的。它可以自动地打开和关闭连接,并维护一个空闲的连接池。

连接池的配置选项可通过options.ClientOptions配置。


```go

// 调用NewClient创建Client对象,并调用Connect方法初始化它。

func Connect(ctx context.Context, opts ...*options.ClientOptions) (*Client, error)

// 创建client对象

func NewClient(opts ...*options.ClientOptions) (*Client, error)


// 通过启动后台监听协程来初始化Client,如果c通过NewClient函数创建,该方法必须在client使用之前被调用。

func (c *Client) Connect(ctx context.Context) error

// 关闭网络连接

func (c *Client) Disconnect(ctx context.Context) error

// Ping 用于验证连接是否建立起来了(与数据库的网络连接)

func (c *Client) Ping(ctx context.Context, rp *readpref.ReadPref) error


// 根据给定的选项创建一个新的会话,调用StartSession是线程安全的,但是返回的session不是线程安全的。

func (c *Client) StartSession(opts ...*options.SessionOptions) (Session, error)


// 获取数据库句柄

func (c *Client) Database(name string, opts ...*options.DatabaseOptions) *Database

func (c *Client) ListDatabases(ctx context.Context, filter interface{}, opts ...*options.ListDatabasesOptions)

func (c *Client) ListDatabaseNames(ctx context.Context, filter interface{}, opts ...*options.ListDatabasesOptions) ([]string, error)


// session

func WithSession(ctx context.Context, sess Session, fn func(SessionContext) error) error

func (c *Client) UseSession(ctx context.Context, fn func(SessionContext) error) error

func (c *Client) UseSessionWithOptions(ctx context.Context, opts *options.SessionOptions, fn func(SessionContext) error) error

func (c *Client) NumberSessionsInProgress() int


// changestream

func (c *Client) Watch(ctx context.Context, pipeline interface{},

opts ...*options.ChangeStreamOptions) (*ChangeStream, error)

```


#### Database

描述一个mongoDB数据库,是线程安全的。

```go

// 获得一个集合句柄

func (db *Database) Collection(name string, opts ...*options.CollectionOptions) *Collection

// 在数据库上执行一个聚合命令

func (db *Database) Aggregate(ctx context.Context, pipeline interface{},

opts ...*options.AggregateOptions) (*Cursor, error)

// 执行命令

func (db *Database) RunCommand(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) *SingleResult

func (db *Database) RunCommandCursor(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) (*Cursor, error)


// 在数据库上删除

func (db *Database) Drop(ctx context.Context) error


// 列出集合

func (db *Database) ListCollectionSpecifications(ctx context.Context, filter interface{},

opts ...*options.ListCollectionsOptions) ([]*CollectionSpecification, error)

func (db *Database) ListCollections(ctx context.Context, filter interface{}, opts ...*options.ListCollectionsOptions) (*Cursor, error)


// 数据库ChangeStream

func (db *Database) Watch(ctx context.Context, pipeline interface{},

opts ...*options.ChangeStreamOptions) (*ChangeStream, error)


// 显示的创建集合,如果集合存在,返回错误

func (db *Database) CreateCollection(ctx context.Context, name string, opts ...*options.CreateCollectionOptions) error

// 创建视图,视图是干什么的?

func (db *Database) CreateView(ctx context.Context, viewName, viewOn string, pipeline interface{},

opts ...*options.CreateViewOptions) error

```


#### Collection

描述一个mongoDB集合,是线程安全的。

```go

// 执行一个批量写操作

func (coll *Collection) BulkWrite(ctx context.Context, models []WriteModel,

opts ...*options.BulkWriteOptions) (*BulkWriteResult, error)


// 插入

func (coll *Collection) InsertOne(ctx context.Context, document interface{},

opts ...*options.InsertOneOptions) (*InsertOneResult, error)

func (coll *Collection) InsertMany(ctx context.Context, documents []interface{},

opts ...*options.InsertManyOptions) (*InsertManyResult, error)


// 删除

func (coll *Collection) DeleteOne(ctx context.Context, filter interface{},

opts ...*options.DeleteOptions) (*DeleteResult, error)

func (coll *Collection) DeleteMany(ctx context.Context, filter interface{},

opts ...*options.DeleteOptions) (*DeleteResult, error)


// 更新

func (coll *Collection) UpdateByID(ctx context.Context, id interface{}, update interface{},

opts ...*options.UpdateOptions) (*UpdateResult, error)

func (coll *Collection) UpdateOne(ctx context.Context, filter interface{}, update interface{},

opts ...*options.UpdateOptions) (*UpdateResult, error)

func (coll *Collection) UpdateMany(ctx context.Context, filter interface{}, update interface{},

opts ...*options.UpdateOptions) (*UpdateResult, error)

func (coll *Collection) ReplaceOne(ctx context.Context, filter interface{},

replacement interface{}, opts ...*options.ReplaceOptions) (*UpdateResult, error)


// 执行聚合命令

func (coll *Collection) Aggregate(ctx context.Context, pipeline interface{},

opts ...*options.AggregateOptions) (*Cursor, error)

// 统计文档数量

func (coll *Collection) CountDocuments(ctx context.Context, filter interface{},

opts ...*options.CountOptions) (int64, error)

func (coll *Collection) EstimatedDocumentCount(ctx context.Context,

opts ...*options.EstimatedDocumentCountOptions) (int64, error)


func (coll *Collection) Distinct(ctx context.Context, fieldName string, filter interface{},

opts ...*options.DistinctOptions) ([]interface{}, error)


// 查询

func (coll *Collection) Find(ctx context.Context, filter interface{},

opts ...*options.FindOptions) (cur *Cursor, err error)

func (coll *Collection) FindOne(ctx context.Context, filter interface{},

opts ...*options.FindOneOptions) *SingleResult

func (coll *Collection) FindOneAndDelete(ctx context.Context, filter interface{},

opts ...*options.FindOneAndDeleteOptions) *SingleResult

func (coll *Collection) FindOneAndReplace(ctx context.Context, filter interface{},

replacement interface{}, opts ...*options.FindOneAndReplaceOptions) *SingleResult

func (coll *Collection) FindOneAndUpdate(ctx context.Context, filter interface{},

update interface{}, opts ...*options.FindOneAndUpdateOptions) *SingleResult

// 监听

func (coll *Collection) Watch(ctx context.Context, pipeline interface{},

opts ...*options.ChangeStreamOptions) (*ChangeStream, error)

// 索引视图

func (coll *Collection) Indexes() IndexView

// 销毁

func (coll *Collection) Drop(ctx context.Context) error

```


#### ___Cursor___

用于迭代文档流。通过Decode或者通过Current字典访问原始的BSON都可以将一个数据库文档解码为一个Go类型。不是线程安全的哦

```go

func (c *Cursor) Next(ctx context.Context) bool

func (c *Cursor) TryNext(ctx context.Context) bool

// 将bson反序列化到val中

func (c *Cursor) Decode(val interface{})

func (c *Cursor) Err() error

func (c *Cursor) Close(ctx context.Context) error

func (c *Cursor) All(ctx context.Context, results interface{}) error

```

新手使用mongodb的评论 (共 条)

分享到微博请遵守国家法律