配置mongodb数据库 以及 数据库web管理mongo-express UI 在Windows上wsl2 Docker
确保你配置好了Docker -> windows上wsl2引擎安装Docker教程https://www.cnblogs.com/eternalnight/p/15173158.html
// 拉取mongodb镜像 docker pull mongo docker network create --subnet=172.16.0.0/16 docker-network // 运行容器 映射27017端口也是mongodb默认端口, --rm 是只运行一次结束时会自动清除。如果想持久就改成 -it即可 --auth 验证账号密码 docker run -d -p 27017:27017 --network docker-network --ip 172.16.0.102 --name mongo_master -e "MONGO_INITDB_ROOT_USERNAME=pudge" -e "MONGO_INITDB_ROOT_PASSWORD=9527" mongo // 再开一个窗口进入mongodb配置账号, 以管理权限进入. docker exec -it mongo_master mongo admin // 用管理权限进入 docker exec -it mongo_master mongo --host 127.0.0.1 --port 27017 -u "pudge" -p "9527" --authenticationDatabase "admin"
// 一定要用use 否则就会默认在test创建用户
use admin; db.createUser({ user: 'pudge', pwd: '9527', roles: [ { role: "root", db: "admin" } ] }); // 验证账号 1 代码正常 db.auth("pudge", "9527"); exit; docker exec -it mongo_master mongo --host 127.0.0.1 --port 27017 -u "pudge" -p "9527" --authenticationDatabase "admin" // 创建db库用户和权限,先得use这个库会自动创建 use PudgeDB; // 创建只有读写权限的账号和分配app数据库 db.createUser({ user: 'pudge', pwd: '9527', roles: [ { role: "readWrite", db: "PudgeDB" } ] }); db.auth("pudge", "9527"); exit
图形工具管理, 这里推荐的两种UI的搭建方式。 docker 或node.js
// 接着用docker操作一遍吧 docker pull mongo-express // 成功了之前原因是docker容器无法识别localhost或127.0.0.1必须有域名或者 host.docker.internal docker run -it --name mongo_ui --network docker-network --ip 172.16.0.103 -p 8081:8081 -e ME_CONFIG_BASICAUTH_USERNAME="pudge" -e ME_CONFIG_BASICAUTH_PASSWORD="9527" -e ME_CONFIG_MONGODB_URL="mongodb://pudge:9527@host.docker.internal:27017/admin?ssl=false" -e ME_CONFIG_MONGODB_AUTH_DATABASE="admin" -e ME_CONFIG_MONGODB_AUTH_USERNAME="pudge" -e ME_CONFIG_MONGODB_AUTH_PASSWORD="9527" mongo-express // node.js版本在16.7.0 建议用 nvm管理node.js版本 npm install -g mongo-express // 前往node.js cd F: vmv16.7.0 ode_modulesmongo-express copy config.default.js config.js
把config.js的内容配置如下, 由于官方的要求是全局变量配置, 但我这觉得太麻烦, 就直接改了能用就行。
'use strict'; let mongo = { // Setting the connection string will only give access to that database // to see more databases you need to set mongodb.admin to true or add databases to the mongodb.auth list // It is RECOMMENDED to use connectionString instead of individual params, other options will be removed later. // More info here: https://docs.mongodb.com/manual/reference/connection-string/ connectionString: process.env.ME_CONFIG_MONGODB_SERVER ? '' : process.env.ME_CONFIG_MONGODB_URL, host: '127.0.0.1', port: '27017', dbName: 'PudgeDB', }; // Accessing Bluemix variable to get MongoDB info if (process.env.VCAP_SERVICES) { const dbLabel = 'mongodb-2.4'; const env = JSON.parse(process.env.VCAP_SERVICES); if (env[dbLabel]) { mongo = env[dbLabel][0].credentials; } } const basicAuthUsername = 'ME_CONFIG_BASICAUTH_USERNAME'; const basicAuthPassword = 'ME_CONFIG_BASICAUTH_PASSWORD'; const adminUsername = 'ME_CONFIG_MONGODB_ADMINUSERNAME'; const adminPassword = 'ME_CONFIG_MONGODB_ADMINPASSWORD'; const dbAuthUsername = 'ME_CONFIG_MONGODB_AUTH_USERNAME'; const dbAuthPassword = 'ME_CONFIG_MONGODB_AUTH_PASSWORD'; function getFile(filePath) { if (typeof filePath !== 'undefined' && filePath) { const fs = require('fs'); try { if (fs.existsSync(filePath)) { return fs.readFileSync(filePath); } } catch (err) { console.error('Failed to read file', filePath, err); } } return null; } function getFileEnv(envVariable) { const origVar = process.env[envVariable]; const fileVar = process.env[envVariable + '_FILE']; if (fileVar) { const file = getFile(fileVar); if (file) { return file.toString().split(/ ? /)[0].trim(); } } return origVar; } function getBinaryFileEnv(envVariable) { const fileVar = process.env[envVariable]; return getFile(fileVar); } const meConfigMongodbServer = process.env.ME_CONFIG_MONGODB_SERVER ? process.env.ME_CONFIG_MONGODB_SERVER.split(',') : false; const INFOS = { username: "pudge", password: "9527", server: "localhost", port: "27017", dbName: "PudgeDB", } function getConnectionStringFromEnvVariables() { const infos = { // server: mongodb hostname or IP address // for replica set, use array of string instead server: ( meConfigMongodbServer.length > 1 ? meConfigMongodbServer : meConfigMongodbServer[0] ) || mongo.host, port: process.env.ME_CONFIG_MONGODB_PORT || mongo.port, dbName: process.env.ME_CONFIG_MONGODB_AUTH_DATABASE || mongo.dbName, // >>>> If you are using an admin mongodb account, or no admin account exists, fill out section below // >>>> Using an admin account allows you to view and edit all databases, and view stats // leave username and password empty if no admin account exists username: getFileEnv(adminUsername) || getFileEnv(dbAuthUsername) || mongo.username, password: getFileEnv(adminPassword) || getFileEnv(dbAuthPassword) || mongo.password, }; const login = INFOS.username ? `${INFOS.username}:${INFOS.password}@` : ''; return `mongodb://${login}${INFOS.server}:${INFOS.port}/${INFOS.dbName}`; } const sslCA = 'ME_CONFIG_MONGODB_CA_FILE'; const sslCAFromEnv = getBinaryFileEnv(sslCA); module.exports = { mongodb: { // if a connection string options such as server/port/etc are ignored connectionString: mongo.connectionString || getConnectionStringFromEnvVariables(), connectionOptions: { // ssl: connect to the server using secure SSL ssl: process.env.ME_CONFIG_MONGODB_SSL || mongo.ssl, // sslValidate: validate mongod server certificate against CA sslValidate: process.env.ME_CONFIG_MONGODB_SSLVALIDATE || true, // sslCA: array of valid CA certificates sslCA: sslCAFromEnv ? [sslCAFromEnv] : [], // autoReconnect: automatically reconnect if connection is lost autoReconnect: true, // poolSize: size of connection pool (number of connections to use) poolSize: 4, }, // set admin to true if you want to turn on admin features // if admin is true, the auth list below will be ignored // if admin is true, you will need to enter an admin username/password below (if it is needed) admin: process.env.ME_CONFIG_MONGODB_ENABLE_ADMIN ? process.env.ME_CONFIG_MONGODB_ENABLE_ADMIN.toLowerCase() === 'true' : false, // whitelist: hide all databases except the ones in this list (empty list for no whitelist) whitelist: [], // blacklist: hide databases listed in the blacklist (empty list for no blacklist) blacklist: [], }, site: { // baseUrl: the URL that mongo express will be located at - Remember to add the forward slash at the start and end! baseUrl: process.env.ME_CONFIG_SITE_BASEURL || '/', cookieKeyName: 'mongo-express', cookieSecret: process.env.ME_CONFIG_SITE_COOKIESECRET || 'cookiesecret', host: process.env.VCAP_APP_HOST || 'localhost', port: process.env.VCAP_APP_PORT || 8081, requestSizeLimit: process.env.ME_CONFIG_REQUEST_SIZE || '50mb', sessionSecret: process.env.ME_CONFIG_SITE_SESSIONSECRET || 'sessionsecret', sslCert: process.env.ME_CONFIG_SITE_SSL_CRT_PATH || '', sslEnabled: process.env.ME_CONFIG_SITE_SSL_ENABLED || false, sslKey: process.env.ME_CONFIG_SITE_SSL_KEY_PATH || '', }, // set useBasicAuth to true if you want to authenticate mongo-express logins // if admin is false, the basicAuthInfo list below will be ignored // this will be true unless ME_CONFIG_BASICAUTH_USERNAME is set and is the empty string useBasicAuth: getFileEnv(basicAuthUsername) !== '', basicAuth: { username: getFileEnv(basicAuthUsername) || 'pudge', password: getFileEnv(basicAuthPassword) || '9527', }, options: { // Display startup text on console console: true, // documentsPerPage: how many documents you want to see at once in collection view documentsPerPage: 10, // editorTheme: Name of the theme you want to use for displaying documents // See http://codemirror.net/demo/theme.html for all examples editorTheme: process.env.ME_CONFIG_OPTIONS_EDITORTHEME || 'rubyblue', // Maximum size of a single property & single row // Reduces the risk of sending a huge amount of data when viewing collections maxPropSize: (100 * 1000), // default 100KB maxRowSize: (1000 * 1000), // default 1MB // The options below aren't being used yet // cmdType: the type of command line you want mongo express to run // values: eval, subprocess // eval - uses db.eval. commands block, so only use this if you have to // subprocess - spawns a mongo command line as a subprocess and pipes output to mongo express cmdType: 'eval', // subprocessTimeout: number of seconds of non-interaction before a subprocess is shut down subprocessTimeout: 300, // readOnly: if readOnly is true, components of writing are not visible. readOnly: process.env.ME_CONFIG_OPTIONS_READONLY ? process.env.ME_CONFIG_OPTIONS_READONLY.toLowerCase() === 'true' : false, // collapsibleJSON: if set to true, jsons will be displayed collapsible collapsibleJSON: true, // collapsibleJSONDefaultUnfold: if collapsibleJSON is set to `true`, this defines default level // to which JSONs are displayed unfolded; use number or "all" to unfold all levels collapsibleJSONDefaultUnfold: 1, // gridFSEnabled: if gridFSEnabled is set to 'true', you will be able to manage uploaded files // ( ak. grids, gridFS ) gridFSEnabled: process.env.ME_CONFIG_SITE_GRIDFS_ENABLED ? process.env.ME_CONFIG_SITE_GRIDFS_ENABLED.toLowerCase() === 'true' : false, // logger: this object will be used to initialize router logger (morgan) logger: {}, // confirmDelete: if confirmDelete is set to 'true', a modal for confirming deletion is // displayed before deleting a document/collection confirmDelete: false, // noExport: if noExport is set to true, we won't show export buttons noExport: false, // noDelete: if noDelete is set to true, we won't show delete buttons noDelete: process.env.ME_CONFIG_OPTIONS_NO_DELETE || false, }, // Specify the default keyname that should be picked from a document to display in collections list. // Keynames can be specified for every database and collection. // If no keyname is specified, it defaults to '_id', which is a mandatory field. // For Example : // defaultKeyNames{ // "world_db":{ //Database Name // "continent":"cont_name", // collection:field // "country":"country_name", // "city":"name" // } // } defaultKeyNames: { }, };
这个步骤只有用node.js才需要
// 这种需要设置了全局才能用 -g mongo-express // 如果不想全局就在app目录运行 node app.js
//访问http://pudge:9527@localhost:8081
命令行操作
内建的角色 数据库用户角色:read、readWrite; 数据库管理角色:dbAdmin、dbOwner、userAdmin; 集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager; 备份恢复角色:backup、restore; 所有数据库角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase 超级用户角色:root // 这里还有几个角色间接或直接提供了系统超级用户的访问(dbOwner 、userAdmin、userAdminAnyDatabase) 内部角色:__system 角色说明: Read:允许用户读取指定数据库 readWrite:允许用户读写指定数据库 dbAdmin:允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问system.profile userAdmin:允许用户向system.users集合写入,可以找指定数据库里创建、删除和管理用户 clusterAdmin:只在admin数据库中可用,赋予用户所有分片和复制集相关函数的管理权限。 readAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读权限 readWriteAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读写权限 userAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的userAdmin权限 dbAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的dbAdmin权限。 root:只在admin数据库中可用。超级账号,超级权限
db操作
> db.dropDatabase() #删除当前使用数据库>
db.cloneDatabase("127.0.0.1") #将指定机器上的数据库的数据克隆到当前数据库>
db.copyDatabase("mydb", "temp", "127.0.0.1") #将本机的mydb的数据复制到temp数据库中>
db.repairDatabase() #修复当前数据库> db.getName() #查看当前使用的数据库,也可以直接用db>
db.stats() #显示当前db状态>
db.version() #当前db版本>
db.getMongo() #查看当前db的链接机器地址>
db.serverStatus() #查看数据库服务器的状态
基础操作
// 查看当前数据库状态
db.stats();db;
// 命令查询所有数据库列表;
show dbs;
// 切换数据库
use app;
// 查看数据库表
db.sirius.stats();
// 帮助 可以按Tab枚举, 也可以输入以下命令
db.help();
// 显示表
show collections;
// 删除当前库
db.dropDatabase();
// 删除账号
db.dropUser("pudge_rw");
// 删除所有账号
db.dropAllUser();
// 删除指定的集合(当前为user集合)
db.user.drop();
// user表中插入数据
db.user.insert({"name":"pudge"});
(1). 查询所有记录 db.user.find(); 类似 SELECT* FROM user; (2). 查询当前集合中的某列去重后的数据 db.user.distinct("name"); 以上会过滤掉 name 中的相同数据 类似 SELECT DISTINCT name FROM user; (3). 查询 age = 22 的记录 db.user.find({"age": 22}); 类似 SELECT* FROM user; (4). 查询 age > 22 的记录 db.user.find({age: {$gt: 22}}); 类似 SELECT* FROM user WHERE age >22; (5). 查询 age < 22 的记录 db.user.find({age: {$lt: 22}}); 类似 SELECT* FROM user WHERE age <22; (6). 查询 age >= 25 的记录 db.user.find({age: {$gte: 25}}); 类似 SELECT* FROM user WHERE age >= 25; (7). 查询 age <= 25 的记录 db.user.find({age: {$lte: 25}}); 类似 SELECT* FROM user WHERE age <= 25; (8). 查询 age >= 23 并且 age <= 26 db.user.find({age: {$gte: 23, $lte: 26}}); 类似 SELECT* FROM user WHERE age >= 25 AND age<=26; (9). 查询 name 中包含 mongo 的数据,多用于模糊查询搜索 db.user.find({name: /mongo/}); 类似 SELECT* FROM user WHERE name LIKE '%mongo%'; (10). 查询 name 中以 mongo 开头的数据 db.user.find({name: /^mongo/}); 类似 SELECT* FROM user WHERE name LIKE 'mongo%'; (11). 查询指定列 name、age 数据 db.user.find({}, {name: 1, age: 1}); 类似 SELECT name, age FROM user; name 也可以用 true 或 false,ture 的情况下与name:1 效果一样,如果用 false 就 是排除 name,显示其它列的信息。 (12). 查询指定列 name、age 数据, 并且age > 25 db.user.find({age: {$gt: 25}}, {name: 1, age: 1}); 类似 SELECT name, age FROM user WHERE age >25; (13). 按照列排序 1 升序 -1 降序 升序:db.user.find().sort({age: 1}); 降序:db.user.find().sort({age: -1}); (14). 查询 name = zhangsan, age = 22 的数据 db.user.find({name: 'zhangsan', age: 22}); 类似 SELECT * FROM user WHERE name = 'zhangsan' AND age = '22'; (15). 查询前 5 条数据 db.user.find().limit(5); 类似 SELECT TOP 5 * FROM user; (16). 查询 10 条以后的数据 db.user.find().skip(10); 类似SELECT * FROM user WHERE id NOT IN ( SELECT TOP 10 * FROM user ); (17). 查询在 5-10 之间的数据 db.user.find().limit(10).skip(5); 可用于分页,limit 是页大小,skip 是第几页乘以页大小的值 类似SELECT * FROM user LIMIT 5,5 (18). OR 查询 db.user.find({$or: [{age: 22}, {age: 25}]}); 类似SELECT * FROM user WHERE age = 22 OR age = 25; (19). findOne 查询第一条数据 db.user.findOne(); 类似 SELECT TOP 1 * FROM user; 类似 db.user.find().limit(1); (20). 查询某个结果集的记录条数,用于统计数量 db.user.find({age: {$gte: 25}}).count(); 类似 SELECT COUNT(*) FROM user WHERE age >= 25; 如果要返回限制之后的记录数量,要使用 count(true)或者 count(非 0) db.user.find().skip(10).limit(5).count(true); 5. MongoDB数据库更新数据 (1). 查找名字为小明的,把年龄更改为 16 岁 db.user.update({"name":"小明"},{$set:{"age":16}}); (2). 查找英语成绩为 70的人,把年龄更改为 33 岁 db.user.update({"score.english":70},{$set:{"age":33}}); (3). 查找所有性别为男的用户把年龄都改为 33 岁 db.user.update({"sex":"男"},{$set:{"age":33}},{multi: true}); (4). 查找name为小明的用户的信息进行完整替换,注意没有$set了 db.user.update({"name":"小明"},{"name":"大明","age":16}); (5). 查找name为Lisi的用户,将其年龄增加50岁 db.user.update({name: 'Lisi'}, {$inc: {age: 50}}, false, true); 类似UPDATE user SET age = age + 50 WHERE name = 'Lisi'; (6). 查找name为Lisi的用户,将其年龄增加50岁,姓名改为Wangwu db.user.update({name: 'Lisi'}, {$inc: {age: 50}, $set: {name: 'Wangwu'}}, false, true); 类似update users set age = age + 50, name = 'Wangwu' where name = 'Lisi'; 6. MongoDB数据库删除数据 (1). 删除年龄为32的所有用户 db.user.remove({age: 32}); (2). 删除年龄为32的一个用户 db.user.remove( { "age": "32" }, { justOne: true } )
1379号监听员 Pudge