onvno / pokerface

日常技术文章阅读整理
3 stars 0 forks source link

20190812 - Mongodb #59

Open onvno opened 5 years ago

onvno commented 5 years ago

MongoDB文档

英文文档:https://docs.mongodb.com/v3.6/ 中文文档:https://s0docs0mongodb0com.icopy.site/v3.6/

Install

Installing MongoDB on a Mac

Install and Run MongoDB with Homebrew

Open the Terminal app and type brew update. After updating Homebrew brew install mongodb After downloading Mongo, create the “db” directory. This is where the Mongo data files will live. You can create the directory in the default location by running mkdir -p /data/db Make sure that the /data/db directory has the right permissions by running

> sudo chown -R `id -un` /data/db
> # Enter your password

Run the Mongo daemon, in one of your terminal windows run mongod. This should start the Mongo server. Run the Mongo shell, with the Mongo daemon running in one terminal, type mongo in another terminal window. This will run the Mongo shell which is an application to access data in MongoDB. To exit the Mongo shell run quit() To stop the Mongo daemon hit ctrl-c

Install and Run MongoDB by Downloading it Manually

Go to the MongoDB website’s download section and download the correct version of MongoDB. After downloading Mongo move the gzipped tar file (the file with the extension .tgz that you downloaded) to the folder where you want Mongo installed. In this case, we’ll say that we want Mongo to live in our home folder, and so the commands might look something like this:

> cd Downloads
> mv mongodb-osx-x86_64-3.0.7.tgz ~/

Extract MongoDB from the the downloaded archive, and change the name of the directory to something more palatable: > cd ~/ > tar -zxvf mongodb-osx-x86_64-3.0.7.tgz > mv mongodb-osx-x86_64-3.0.7 mongodb

Create the directory where Mongo will store data, create the “db” directory. ou can create the directory in the default location by running mkdir -p /data/db Make sure that the /data/db directory has the right permissions by running

> sudo chown -R `id -un` /data/db
> # Enter your password

Run the Mongo daemon, in one terminal window run ~/mongodb/bin/mongod. This will start the Mongo server. Run the Mongo shell, with the Mongo daemon running in one terminal, type ~/mongodb/bin/mongo in another terminal window. This will run the Mongo shell which is an application to access data in MongoDB. To exit the Mongo shell run quit() To stop the Mongo daemon hit ctrl-c

onvno commented 5 years ago

可视化工具

Robo 3T 是一款叫mongodb 可视化工具, 是一个免费版本,还有个付费版本叫Studio 3T 官网 https://robomongo.org/

onvno commented 5 years ago

Mongoodb自增

mongoose-auto-increment

// 链接数据库init
const CONFIG = require('../config/index.js');

const mongoose = require('mongoose');
const autoIncrement = require('mongoose-auto-increment');

const {uri, opts} = CONFIG.db;

mongoose.connect(uri, opts)

const db = mongoose.connection;
autoIncrement.initialize(mongoose);

单一Model使用

const mongoose = require('mongoose');
const autoIncrement = require('mongoose-auto-increment');

const Schema = mongoose.Schema;

const userSchema = new Schema({
  user_name: String,
  create_time: String,
  status: Number,//1:普通管理、 2:超级管理员
})

userSchema.plugin(autoIncrement.plugin, 'User')
const User = mongoose.model('User', userSchema);
module.exports = User;
onvno commented 4 years ago
onvno commented 4 years ago

MongoDB数据库设计

onvno commented 4 years ago

MongoDB 中的索引和 Mongoose 中的 autoIndex

onvno commented 4 years ago

Mongodb索引

  1. MongoDB索引原理:推荐阅读
  2. MongoDB索引管理——创建索引,查看索引,删除索引,重建索引
  3. 正确理解和使用 Mongodb 的索引
onvno commented 4 years ago

删除嵌套数组方法:mongo 删除内嵌数组元素

mongodb文档:https://docs.mongodb.com/manual/reference/operator/update/pull/

onvno commented 4 years ago

MongoDB在58同城百亿量级数据下的应用实践 参考上文,考虑方便查询,减少索引创建,部分集合使用特殊_id.

How to set _id to db document in Mongoose?

var Post = new mongoose.Schema({
    _id: Number,
    title: String,
    content: String,
    tags: [ String ]
});

var Post = new mongoose.Schema({
    title: String,
    content: String,
    tags: [ String ]
}, { _id: false });
onvno commented 4 years ago

Mongodb条件查询:MongoDB的条件查询

查询有常用的:小于("$lt")、小于等于("$lte")、大于("$gt")、大于等于("$gte")、不等于("$ne")

#查询年龄大于20且小于30的用户  
db.users.find({"age":{"$gt":20, "$lte":23}})

对单一键有多个值与其匹配的话就用"$in",后面跟一个条件数组。

#查询年龄在某个范围的用户:  
db.users.find({"age":{"$in":[20, 22, 25]}})  

与单一键的"$in"不同的是,"$or"是包含多个可能条件的数组。

#年龄在某个范围内或者name在某个范围内的用户  
db.users.find({"$or": [{"age": 23 }, {"name": "robin"}]})  
db.users.find({"$or": [{"age": {"$in": [ 23, 4, "az" ]} }, {"name": "robin"}]})  

测试$or包含的不能是字符串`

 {
    "errcode": 409,
    "errmsg": "Can't use $or with String.",
    "data": null
}
onvno commented 4 years ago

返回字段

作为查询的第二个参数,如果没有的话是默认返回所有字段。可以对需要的返回字段指定:

db.users.find({}, {"name":1, "age":1}) 

1、这个查询会返回name、age、_id字段 2、_id是默认返回,如果不要显示加上("_id":0)

db.users.find({}, {"name":1, "age":1, "_id":0})

后台自运行 MongoDB之旅:MongDB安装和使用(后台运行)

onvno commented 4 years ago

mongodb linux安装

Linux平台安装MongoDB

下载完安装包,并解压 tgz(以下演示的是 64 位 Linux上的安装) 。

curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.0.6.tgz    # 下载
tar -zxvf mongodb-linux-x86_64-3.0.6.tgz                                   # 解压

mv  mongodb-linux-x86_64-3.0.6/ /usr/local/mongodb                         # 将解压包拷贝到指定目录

MongoDB 的可执行文件位于 bin 目录下,所以可以将其添加到 PATH 路径中:

export PATH=<mongodb-install-directory>/bin:$PATH
onvno commented 4 years ago

设置Auth

  1. 连接数据库

  2. 进入客户端

    mongo

    3.设置全局用户信息

    use admin
    db.createUser({user: 'root', pwd: '123456', roles: ['root']})

    设置完成后校验用户是否生效

    db.auth(用户名,用户密码)

    这里用db.auth('root', '123456') 如果返回 '1'表示验证成功, 如果是 '0' 表示验证失败...

  3. 给单独的库设置密码,以Article为例

    use Article
    db.createUser({user:'zwVic',pwd:'adgjmp123',roles: [{role:'readWrite',db:'Article'}]})})

    创建一个zwStar用户 给予读写权限 db表示该用户操作的数据库名

以上设置完成,一下为连接数据库

  1. 连接mongodb
    mongod --dbpath 存放数据库文件夹路径 --auth
  2. 连接加密数据库
    #客户端连接并认证
    >mongo
    >use foo
    >db.auth(“simpleUser”,”123456”)

补充: 查看用户:db.system.users.find() 删除用户:db.system.users.remove({user:”simpleUser”}) 注:在操作用户时,启动mongod服务时尽量不开启授权

以上参考自: 给你的mongodb设置密码吧! MongoDB开启权限验证及设置用户名密码

onvno commented 4 years ago

BSON的介绍及BSON与JSON的区别

BSON是由10gen开发的一个数据格式,目前主要用于MongoDB中,是mongodb的数据存储格式。BSON基于JSON格式,选择JSON进行改造的原因主要是JSON的通用性及JSON的schemaless的特性。 BSON主要会实现以下三点目标: (1)更快的遍历速度 对JSON格式来说,太大的JSON结构会导致数据遍历非常慢。在JSON中,要跳过一个文档进行数据读取,需要对此文档进行扫描才行,需要进行麻烦的数据结构匹配,比如括号的匹配,而BSON对JSON的一大改进就是,它会将JSON的每一个元素的长度存在元素的头部,这样你只需要读取到元素长度就能直接seek到指定的点上进行读取了。 (2)操作更简易 对JSON来说,数据存储是无类型的,比如你要修改基本一个值,从9到10,由于从一个字符变成了两个,所以可能其后面的所有内容都需要往后移一位才可以。而使用BSON,你可以指定这个列为数字列,那么无论数字从9长到10还是100,我们都只是在存储数字的那一位上进行修改,不会导致数据总长变大。当然,在MongoDB中,如果数字从整形增大到长整型,还是会导致数据总长变大的。 (3)增加了额外的数据类型 JSON是一个很方便的数据交换格式,但是其类型比较有限。BSON在其基础上增加了“byte array”数据类型。这使得二进制的存储不再需要先base64转换后再存成JSON。大大减少了计算开销和数据大小。 但是,在有的时候,BSON相对JSON来说也并没有空间上的优势,比如对{“field”:7},在JSON的存储上7只使用了一个字节,而如果用BSON,那就是至少4个字节(32位) 目前在10gen的努力下,BSON已经有了针对多种语言的编码解码包。并且都是Apache 2 license下开源的。并且还在随着MongoDB进一步地发展。

———————————————— 版权声明:本文为CSDN博主「浮生忆梦」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/m0_38110132/article/details/77716792

onvno commented 4 years ago

MAC升级系统Catalina注意问题

1.默认数据库存储地址不可写入 解决办法:更换地址

$ mongod --dbpath=/Users/user/data/db

2.更换数据库地址写入仍不成功 解决办法:目录写入权限

$ sudo chmod -R go+w /data/db
onvno commented 4 years ago

mongodb的配置文件,一般存放目录:/etc/mongod.conf

systemLog:
   # verbosity: 0  #日志等级,0-5,默认0
   # quiet: false  #限制日志输出,
   # traceAllExceptions: true  #详细错误日志
   # syslogFacility: user #记录到操作系统的日志级别,指定的值必须是操作系统支持的,并且要以--syslog启动
   path: /Users/mhq/projects/db/mongo/logs/log.txt  #日志路径。
   logAppend: false #启动时,日志追加在已有日志文件内还是备份旧日志后,创建新文件记录日志, 默认false
   logRotate: rename #rename/reopen。rename,重命名旧日志文件,创建新文件记录;reopen,重新打开旧日志记录,需logAppend为true
   destination: file #日志输出方式。file/syslog,如果是file,需指定path,默认是输出到标准输出流中
   timeStampFormat: iso8601-local #日志日期格式。ctime/iso8601-utc/iso8601-local, 默认iso8601-local
   # component: #各组件的日志级别
   #    accessControl:
   #       verbosity: <int>
   #    command:
   #       verbosity: <int>

processManagement:
   fork: true #以守护进程运行 默认false
   # pidFilePath: <string> #PID 文件位置

net:
   port: 27017 #监听端口,默认27017
   bindIp: 127.0.0.1 #绑定监听的ip,deb和rpm包里有默认的配置文件(/etc/mongod.conf)里面默认配置为127.0.0.1,若不限制IP,务必确保认证安全,多个Ip用逗号分隔
   maxIncomingConnections: 65536 #最大连接数,可接受的连接数还受限于操作系统配置的最大连接数
   wireObjectCheck: true #校验客户端的请求,防止错误的或无效BSON插入,多层文档嵌套的对象会有轻微性能影响,默认true
   ipv6: false #是否启用ipv6,3.0以上版本始终开启
   unixDomainSocket: #unix socket监听,仅适用于基于unix的系统
      enabled: false #默认true
      pathPrefix: /tmp #路径前缀,默认/temp
      filePermissions: 0700 #文件权限 默认0700
   http: #警告 确保生产环境禁用HTTP status接口、REST API以及JSON API以防止数据暴露和漏洞攻击
      enabled: false #是否启用HTTP接口、启用会增加网络暴露。3.2版本后停止使用HTTP interface
      JSONPEnabled: false #JSONP的HTTP接口
      RESTInterfaceEnabled: false #REST API接口
   # ssl: #估计用不到,所以没有自己看
   #    sslOnNormalPorts: <boolean>  # deprecated since 2.6
   #    mode: <string>
   #    PEMKeyFile: <string>
   #    PEMKeyPassword: <string>
   #    clusterFile: <string>
   #    clusterPassword: <string>
   #    CAFile: <string>
   #    CRLFile: <string>
   #    allowConnectionsWithoutCertificates: <boolean>
   #    allowInvalidCertificates: <boolean>
   #    allowInvalidHostnames: <boolean>
   #    disabledProtocols: <string>
   #    FIPSMode: <boolean>

security:
   authorization: enabled # enabled/disabled #开启客户端认证
   javascriptEnabled:  true #启用或禁用服务器端JavaScript执行
   # keyFile: <string> #密钥路径
   # clusterAuthMode: <string> #集群认证方式
   # enableEncryption: <boolean>
   # encryptionCipherMode: <string>
   # encryptionKeyFile: <string>
   # kmip:
   #    keyIdentifier: <string>
   #    rotateMasterKey: <boolean>
   #    serverName: <string>
   #    port: <string>
   #    clientCertificateFile: <string>
   #    clientCertificatePassword: <string>
   #    serverCAFile: <string>
   # sasl:
   #    hostName: <string>
   #    serviceName: <string>
   #    saslauthdSocketPath: <string>

# setParameter: #设置参数
#    <parameter1>: <value1>
#    <parameter2>: <value2>

storage:
   dbPath: /Users/mhq/projects/db/mongo/test/ #数据库,默认/data/db,如果使用软件包管理安装的查看/etc/mongod.conf
   indexBuildRetry: true #重启时,重建不完整的索引
   # repairPath: <string>  #--repair操作时的临时工作目录,默认为dbPath下的一个_tmp_repairDatabase_<num>的目录
   journal: 
      enabled: true #启动journal,64位系统默认开启,32位默认关闭
      # commitIntervalMs: <num> #journal操作的最大时间间隔,默认100或30
   directoryPerDB: false #使用单独的目录来存储每个数据库的数据,默认false,如果需要更改,要备份数据,删除掉dbPath下的文件,重建后导入数据
   # syncPeriodSecs: 60 #使用fsync来将数据写入磁盘的延迟时间量,建议使用默认值
   engine: wiredTiger #存储引擎,mmapv1/wiredTiger/inMemory 默认wiredTiger
   # mmapv1:
   #    preallocDataFiles: <boolean>
   #    nsSize: <int>
   #    quota:
   #       enforced: <boolean>
   #       maxFilesPerDB: <int>
   #    smallFiles: <boolean>
   #    journal:
   #       debugFlags: <int>
   #       commitIntervalMs: <num>
   # wiredTiger:
   #    engineConfig:
   #       cacheSizeGB: <number>  #缓存大小
   #       journalCompressor: <string> #数据压缩格式 none/snappy/zlib
   #       directoryForIndexes: <boolean> #将索引和集合存储在单独的子目录下,默认false
   #    collectionConfig:
   #       blockCompressor: <string> #集合数据压缩格式 
   #    indexConfig:
   #       prefixCompression: <boolean> #启用索引的前缀压缩
   # inMemory:
   #    engineConfig:
   #       inMemorySizeGB: <number>

operationProfiling: #性能分析
   slowOpThresholdMs: 100 #认定为查询速度缓慢的时间阈值,超过该时间的查询即为缓慢查询,会被记录到日志中, 默认100
   mode: off #operationProfiling模式 off/slowOp/all 默认off

# replication: #复制集相关
#    oplogSizeMB: <int>
#    replSetName: <string>
#    secondaryIndexPrefetch: <string>
#    enableMajorityReadConcern: <boolean>
# sharding: #集群分片相关
#    clusterRole: <string>
#    archiveMovedChunks: <boolean>

# auditLog:
#    destination: <string>
#    format: <string>
#    path: <string>
#    filter: <string>

# snmp:
#    subagent: <boolean> #当设置为true,SNMP作为代理运行
#    master: <boolean> #当设置为true,SNMP作为主服务器运行

# basisTech:
#    rootDirectory: <string>

配置文件及简单注释(参考官方3.2文档)

onvno commented 4 years ago

启动MongoDB的方式有两种: 1.直接启动,配置参数写在命令中: mongod --dbpath=data/db --logpath=log/log.txt --fork 2.以配置文件启动: mongod -f /etc/mongod.conf 或 mongod --config /etc/mongod.conf

链接:https://www.jianshu.com/p/f179ce608391