MongoDB 数据类型 转
mongodb • lopo1983 发表了文章 • 0 个评论 • 1631 次浏览 • 2018-12-26 16:46
String 2 字符串 - 这是用于存储数据的最常用的数据类型。MongoDB中的字符串必须为UTF-8
Object 3 对象 - 此数据类型用于嵌入式文档
Array 4 数组 - 此类型用于将数组或列表或多个值存储到一个键中
Binary data 5 二进制数据 - 此数据类型用于存储二进制数据
Undefined 6 已废弃
Object id 7 对象ID - 此数据类型用于存储文档的ID
Boolean 8 布尔类型 - 此类型用于存储布尔值(true / false)值
Date 9 日期 - 此数据类型用于以UNIX时间格式存储当前日期或时间。可以通过创建日期对象并将日,月,年的日期进行指定自己需要的日期时间
Null 10 Null - 此类型用于存储Null值
Regular 11 正则表达式 - 此数据类型用于存储正则表达式
JavaScript 13 代码 - 此数据类型用于将JavaScript代码存储到文档中
Symbol 14 符号 - 该数据类型与字符串相同;但是,通常保留用于使用特定符号类型的语言
JavaScript (with scope) 15 代码 - 此数据类型用于将带作用域的JavaScript代码存储到文档中
32-bit integer 16 32位整型 - 此类型用于存储数值
Timestamp 17 时间戳 - 当文档被修改或添加时,可以方便地进行录制
64-bit integer 18 64位整型 - 此类型用于存储数值
Min key 255 最小键 - 此类型用于将值与最小BSON元素进行比较
Max key 127 最大键 - 此类型用于将值与最大BSON元素进行比较
---------------------
作者:_抱歉打扰了
来源:CSDN
原文:https://blog.csdn.net/qq_33661 ... 16603
版权声明:本文为博主原创文章,转载请附上博文链接! 查看全部
Double 1 双精度浮点数 - 此类型用于存储浮点值
String 2 字符串 - 这是用于存储数据的最常用的数据类型。MongoDB中的字符串必须为UTF-8
Object 3 对象 - 此数据类型用于嵌入式文档
Array 4 数组 - 此类型用于将数组或列表或多个值存储到一个键中
Binary data 5 二进制数据 - 此数据类型用于存储二进制数据
Undefined 6 已废弃
Object id 7 对象ID - 此数据类型用于存储文档的ID
Boolean 8 布尔类型 - 此类型用于存储布尔值(true / false)值
Date 9 日期 - 此数据类型用于以UNIX时间格式存储当前日期或时间。可以通过创建日期对象并将日,月,年的日期进行指定自己需要的日期时间
Null 10 Null - 此类型用于存储Null值
Regular 11 正则表达式 - 此数据类型用于存储正则表达式
JavaScript 13 代码 - 此数据类型用于将JavaScript代码存储到文档中
Symbol 14 符号 - 该数据类型与字符串相同;但是,通常保留用于使用特定符号类型的语言
JavaScript (with scope) 15 代码 - 此数据类型用于将带作用域的JavaScript代码存储到文档中
32-bit integer 16 32位整型 - 此类型用于存储数值
Timestamp 17 时间戳 - 当文档被修改或添加时,可以方便地进行录制
64-bit integer 18 64位整型 - 此类型用于存储数值
Min key 255 最小键 - 此类型用于将值与最小BSON元素进行比较
Max key 127 最大键 - 此类型用于将值与最大BSON元素进行比较
---------------------
作者:_抱歉打扰了
来源:CSDN
原文:https://blog.csdn.net/qq_33661 ... 16603
版权声明:本文为博主原创文章,转载请附上博文链接!
openstack gnocchi 服务器硬件监控 (基于Eggjs实现)
openstack • lopo1983 发表了文章 • 0 个评论 • 2279 次浏览 • 2018-12-22 02:51
const ServerIndex = require('../index')
/**
* @name 获取监控数据
* @param {*} _ucid 用户id
* @param {*} server_id 服务器id
* @param {*} type 聚合类型
* @param {*} metric 聚合数据
* @description type和metric 子属关系如下
*
* instance?["vcpus", "memory", "disk.root.size", "compute.instance.booting.time", "cpu_util", "disk.ephemeral.size", "cpu.delta", "cpu", "memory.usage"]
*
* instance_network_interface ["network.outgoing.packets.rate", "network.incoming.bytes.rate", "network.outgoing.bytes.rate", "network.incoming.packets", "network.incoming.packets.rate", "network.outgoing.bytes", "network.incoming.bytes", "network.outgoing.packets"]
*
* instance_disk ["disk.device.read.bytes.rate", "disk.device.write.requests", "disk.device.write.bytes.rate", "disk.device.write.requests.rate", "disk.device.read.bytes", "disk.device.read.requests", "disk.device.read.requests.rate", "disk.device.write.bytes"]
*
*/
class ResourceService extends ServerIndex {
constructor(ctx) {
super(ctx);
this.actions = ':8041/v1/';
}
async getMeasures(_ucid, { server_id, type, metric } = {}) {
const ctx = this.ctx;
const { subtractMoment } = ctx.helper;
try {
const metricIDs = await this.getmetricID(_ucid, server_id, type, metric);
const getDATASFn = metricIDs.map(async e => {
return {
name: e.name,
datas: await this.OSAJax(`${this.actions}metric/${e.id}/measures`, {
body: { start: subtractMoment(1, 'hour') }
})
}
})
const datas = (await Promise.all(getDATASFn)).reduce((a, b) => {
a[`${b['name']}`] = b['datas'];
return a
}, {})
return { data: datas };
} catch (error) {
console.log(error)
return error
}
}
async getmetricID(_ucid, server_id, type, metric) {
const metrics = metric.split(',')
try {
const DATAS = await this.OSAJax(`${this.actions}search/resource/generic/`, {
_ucid,
method: 'POST',
body: {
"and": [
{
"like": {
"original_resource_id": `%${server_id}%`
}
},
{
"=": {
"type": type
}
}
]
}
});
const { code } = DATAS;
if (!code && !!DATAS.length) {
const MAPS = DATAS[0].metrics
return metrics.reduce((a, b) => { a.push({ name: b, id: MAPS[b] }); return a }, )
} else {
return undefined
}
} catch (error) {
return error
}
}
}
module.exports = ResourceService;[/b]?'use strict';
const Service = require('egg').Service;
//
class indexService extends Service {
constructor(ctx) {
super(ctx);
this.OPTokenMODEL = ctx.model.Openstack.Token;
this.OPUserMODEL = ctx.model.Openstack.Identity.User;
this.OBJKeySort = ctx.helper.OBJKeySort;
const { uri } = this.config.openstack;
this.uri = `${uri}`;
this.CurlOpt = async (method, full, token) => {
return {
'dataType': 'json',
'headers': {
...((!full && !token) && { 'X-Auth-Token': (await ctx.helper.TokenFn('openstack')).data }) || !!token && { 'X-Auth-Token': token },
'Content-Type': 'application/json',
},
'method': method,
...method !== 'DELETE' && { 'data': {} },
'timeout': 60000
}
}
};
/**
* 基础库
*
* @param {Object} body 需要提交的参数
* @param {String} method GET POST DELETE PUT PATCH
* @param {String} params url 参数
* @param {Boolean} full 是否显示完整参数
* @param {String} _ucid 用户ID Optional
*/
async OSAJax(params, { body = {}, method = "GET", full = false, status = false, _ucid } = {}) {
const ctx = this.ctx;
const opt = await this.CurlOpt(method, full, !!_ucid && await this.getUserToken(_ucid));
method !== 'DELETE' && Object.assign(opt.data, { ...!!body ? body : '' });
try {
const result = await ctx.curl(`${this.uri}${!!params ? params : ''}`, opt);
return !!full && result || !!status && result.status || result.data;
} catch (error) {
return error
}
}
}
module.exports = indexService; 查看全部
'use strict';?
const ServerIndex = require('../index')
/**
* @name 获取监控数据
* @param {*} _ucid 用户id
* @param {*} server_id 服务器id
* @param {*} type 聚合类型
* @param {*} metric 聚合数据
* @description type和metric 子属关系如下
*
* instance?["vcpus", "memory", "disk.root.size", "compute.instance.booting.time", "cpu_util", "disk.ephemeral.size", "cpu.delta", "cpu", "memory.usage"]
*
* instance_network_interface ["network.outgoing.packets.rate", "network.incoming.bytes.rate", "network.outgoing.bytes.rate", "network.incoming.packets", "network.incoming.packets.rate", "network.outgoing.bytes", "network.incoming.bytes", "network.outgoing.packets"]
*
* instance_disk ["disk.device.read.bytes.rate", "disk.device.write.requests", "disk.device.write.bytes.rate", "disk.device.write.requests.rate", "disk.device.read.bytes", "disk.device.read.requests", "disk.device.read.requests.rate", "disk.device.write.bytes"]
*
*/
class ResourceService extends ServerIndex {
constructor(ctx) {
super(ctx);
this.actions = ':8041/v1/';
}
async getMeasures(_ucid, { server_id, type, metric } = {}) {
const ctx = this.ctx;
const { subtractMoment } = ctx.helper;
try {
const metricIDs = await this.getmetricID(_ucid, server_id, type, metric);
const getDATASFn = metricIDs.map(async e => {
return {
name: e.name,
datas: await this.OSAJax(`${this.actions}metric/${e.id}/measures`, {
body: { start: subtractMoment(1, 'hour') }
})
}
})
const datas = (await Promise.all(getDATASFn)).reduce((a, b) => {
a[`${b['name']}`] = b['datas'];
return a
}, {})
return { data: datas };
} catch (error) {
console.log(error)
return error
}
}
async getmetricID(_ucid, server_id, type, metric) {
const metrics = metric.split(',')
try {
const DATAS = await this.OSAJax(`${this.actions}search/resource/generic/`, {
_ucid,
method: 'POST',
body: {
"and": [
{
"like": {
"original_resource_id": `%${server_id}%`
}
},
{
"=": {
"type": type
}
}
]
}
});
const { code } = DATAS;
if (!code && !!DATAS.length) {
const MAPS = DATAS[0].metrics
return metrics.reduce((a, b) => { a.push({ name: b, id: MAPS[b] }); return a }, )
} else {
return undefined
}
} catch (error) {
return error
}
}
}
module.exports = ResourceService;[/b]
'use strict';
const Service = require('egg').Service;
//
class indexService extends Service {
constructor(ctx) {
super(ctx);
this.OPTokenMODEL = ctx.model.Openstack.Token;
this.OPUserMODEL = ctx.model.Openstack.Identity.User;
this.OBJKeySort = ctx.helper.OBJKeySort;
const { uri } = this.config.openstack;
this.uri = `${uri}`;
this.CurlOpt = async (method, full, token) => {
return {
'dataType': 'json',
'headers': {
...((!full && !token) && { 'X-Auth-Token': (await ctx.helper.TokenFn('openstack')).data }) || !!token && { 'X-Auth-Token': token },
'Content-Type': 'application/json',
},
'method': method,
...method !== 'DELETE' && { 'data': {} },
'timeout': 60000
}
}
};
/**
* 基础库
*
* @param {Object} body 需要提交的参数
* @param {String} method GET POST DELETE PUT PATCH
* @param {String} params url 参数
* @param {Boolean} full 是否显示完整参数
* @param {String} _ucid 用户ID Optional
*/
async OSAJax(params, { body = {}, method = "GET", full = false, status = false, _ucid } = {}) {
const ctx = this.ctx;
const opt = await this.CurlOpt(method, full, !!_ucid && await this.getUserToken(_ucid));
method !== 'DELETE' && Object.assign(opt.data, { ...!!body ? body : '' });
try {
const result = await ctx.curl(`${this.uri}${!!params ? params : ''}`, opt);
return !!full && result || !!status && result.status || result.data;
} catch (error) {
return error
}
}
}
module.exports = indexService;
MongoDB导入导出以及数据库备份
mongodb • lopo1983 发表了文章 • 0 个评论 • 1557 次浏览 • 2018-12-15 04:16
1.概念
mongoDB中的mongoexport工具可以把一个collection导出成JSON格式或CSV格式的文件。可以通过参数指定导出的数据项,也可以根据指定的条件导出数据。
2、语法mongoexport -d dbname -c collectionname -o file --type json/csv -f field
参数说明:
-d :数据库名-c :collection名-o :输出的文件名--type : 输出的格式,默认为json-f :输出的字段,如果-type为csv,则需要加上-f "字段名"
示例mongoexport -d mongotest -c users -o /home/export/mongoDB/users.json --type json -f "_id,user_id,user_name,age,status"
-----------------------------------------------------------------------------------------------------------------
导入
1.语法mongoimport -d dbname -c collectionname --file filename --headerline --type json/csv -f field
参数说明:
-d :数据库名-c :collection名--type :导入的格式默认json-f :导入的字段名--headerline :如果导入的格式是csv,则可以使用第一行的标题作为导入的字段--file :要导入的文件
2.示例mongoimport -d mongotest -c users --file /home/mongodump/articles.json --type json
-----------------------------------------------------------------------------------------------------------------
备份
1.语法mongodump -h dbhost -d dbname -o dbdirectory
参数说明:
-h: MongDB所在服务器地址,例如:127.0.0.1,当然也可以指定端口号:127.0.0.1:27017-d: 需要备份的数据库实例,例如:test-o: 备份的数据存放位置,例如:/home/mongodump/,当然该目录需要提前建立,这个目录里面存放该数据库实例的备份数据。
2.示例sudo rm -rf /home/momgodump/
sudo mkdir -p /home/momgodump
sudo mongodump -h 192.168.17.129:27017 -d itcast -o /home/mongodump/
-----------------------------------------------------------------------------------------------------------------
恢复
1.语法mongorestore -h dbhost -d dbname --dir dbdirectory
参数说明:
-h: MongoDB所在服务器地址-d: 需要恢复的数据库实例,例如:test,当然这个名称也可以和备份时候的不一样,比如test2--dir: 备份数据所在位置,例如:/home/mongodump/itcast/--drop: 恢复的时候,先删除当前数据,然后恢复备份的数据。就是说,恢复后,备份后添加修改的数据都会被删除,慎用!
2.示例mongorestore -h 192.168.17.129:27017 -d itcast_restore --dir /home/mongodump/itcast/ 查看全部
1.概念
mongoDB中的mongoexport工具可以把一个collection导出成JSON格式或CSV格式的文件。可以通过参数指定导出的数据项,也可以根据指定的条件导出数据。
2、语法
mongoexport -d dbname -c collectionname -o file --type json/csv -f field
参数说明:
- -d :数据库名
- -c :collection名
- -o :输出的文件名
- --type : 输出的格式,默认为json
- -f :输出的字段,如果-type为csv,则需要加上-f "字段名"
示例
mongoexport -d mongotest -c users -o /home/export/mongoDB/users.json --type json -f "_id,user_id,user_name,age,status"
-----------------------------------------------------------------------------------------------------------------
导入
1.语法
mongoimport -d dbname -c collectionname --file filename --headerline --type json/csv -f field
参数说明:
- -d :数据库名
- -c :collection名
- --type :导入的格式默认json
- -f :导入的字段名
- --headerline :如果导入的格式是csv,则可以使用第一行的标题作为导入的字段
- --file :要导入的文件
2.示例
mongoimport -d mongotest -c users --file /home/mongodump/articles.json --type json
-----------------------------------------------------------------------------------------------------------------
备份
1.语法
mongodump -h dbhost -d dbname -o dbdirectory
参数说明:
- -h: MongDB所在服务器地址,例如:127.0.0.1,当然也可以指定端口号:127.0.0.1:27017
- -d: 需要备份的数据库实例,例如:test
- -o: 备份的数据存放位置,例如:/home/mongodump/,当然该目录需要提前建立,这个目录里面存放该数据库实例的备份数据。
2.示例
sudo rm -rf /home/momgodump/
sudo mkdir -p /home/momgodump
sudo mongodump -h 192.168.17.129:27017 -d itcast -o /home/mongodump/
-----------------------------------------------------------------------------------------------------------------
恢复
1.语法
mongorestore -h dbhost -d dbname --dir dbdirectory
参数说明:
- -h: MongoDB所在服务器地址
- -d: 需要恢复的数据库实例,例如:test,当然这个名称也可以和备份时候的不一样,比如test2
- --dir: 备份数据所在位置,例如:/home/mongodump/itcast/
- --drop: 恢复的时候,先删除当前数据,然后恢复备份的数据。就是说,恢复后,备份后添加修改的数据都会被删除,慎用!
2.示例
mongorestore -h 192.168.17.129:27017 -d itcast_restore --dir /home/mongodump/itcast/
queries 分离函数 适用 mongoose
Nodejs • lopo1983 发表了文章 • 0 个评论 • 1385 次浏览 • 2018-10-17 21:34
/**
* GET querys 分离函数
* @param {String} pages 分页 [上一页最后一个数据的_id,分页数量] 分页数量默认为10
* @param {String} fields 需要展示的字段 a,b,c,d
* @param {String} unFields 不需要展示的字段 a,b,c,d
* @param {String} querys 查询条件 如 a=1&b=2&c=3
* @param {String} orderBy 排序字段
* @param {String} sort 排序方式【1:正序,-1:倒序】(必须与prderBy同时出现)
* @param {String} dates 时间范围/时间查询 [开始时间,结束时间]/查询时间
*
* @version 1.0.1
* 2018/10/17 修改返回值类型可直接供mongoose使用
*
* @example
* GET /user/?orderBy=compName&sort=-1&pages=20,1&fields=compName,compAuth,compEmail&unFields=status&dates=2018-8-5&name=lopo
* @return {Object}
* {
* querys: { name: 'lopo' },
* select: { compName: 1, compAuth: 1, compEmail: 1, status: 0 },
* pages: { marker: '1', limit: '20' },
* sort: { compName: '-1' },
* dates: '2018-8-5'
* }
*/
queryParamFn(querys) {
const mapFN = (str) => (field, val) => str[field].split(',').reduce((a, b) => { a<strong> = val; return a }, {});
let strToArr = mapFN(querys);
const pages = !!querys.pages && querys.pages;
const orderBy = !!querys.orderBy && querys.orderBy;
const sort = !!querys.sort && querys.sort;
const dates = !!querys.dates && querys.dates;
const fields = !!querys.fields ? strToArr('fields', 1) : {};
const unFields = !!querys.unFields ? strToArr('unFields', 0) : {};
const dateFn = () => {
if (!!dates) {
const ARR = dates.split(',');
return ARR.length === 2 ? { '$gte': ARR[1], '$lte': ARR[0] } : `${ARR}`
}
}
const sortFn = () => {
let OBJ = {};
if (!!orderBy) {
OBJ[orderBy] = sort;
return OBJ
}
return OBJ || {}
}
delete querys.pages;
delete querys.fields;
delete querys.unFields;
delete querys.orderBy;
delete querys.sort;
delete querys.dates;
return {
'querys': querys || {},
'select': { ...fields, ...unFields },
...(!!pages && {
'pages': {
'marker': pages.split(',')[1] || undefined,
'limit': pages.split(',')[0] || 10
}
}),
...!!orderBy && {
'sort': sortFn()
},
...!!dates && {
'dates': dateFn()
}
}
} 查看全部
// app/extend/helper.js
/**
* GET querys 分离函数
* @param {String} pages 分页 [上一页最后一个数据的_id,分页数量] 分页数量默认为10
* @param {String} fields 需要展示的字段 a,b,c,d
* @param {String} unFields 不需要展示的字段 a,b,c,d
* @param {String} querys 查询条件 如 a=1&b=2&c=3
* @param {String} orderBy 排序字段
* @param {String} sort 排序方式【1:正序,-1:倒序】(必须与prderBy同时出现)
* @param {String} dates 时间范围/时间查询 [开始时间,结束时间]/查询时间
*
* @version 1.0.1
* 2018/10/17 修改返回值类型可直接供mongoose使用
*
* @example
* GET /user/?orderBy=compName&sort=-1&pages=20,1&fields=compName,compAuth,compEmail&unFields=status&dates=2018-8-5&name=lopo
* @return {Object}
* {
* querys: { name: 'lopo' },
* select: { compName: 1, compAuth: 1, compEmail: 1, status: 0 },
* pages: { marker: '1', limit: '20' },
* sort: { compName: '-1' },
* dates: '2018-8-5'
* }
*/
queryParamFn(querys) {
const mapFN = (str) => (field, val) => str[field].split(',').reduce((a, b) => { a<strong> = val; return a }, {});
let strToArr = mapFN(querys);
const pages = !!querys.pages && querys.pages;
const orderBy = !!querys.orderBy && querys.orderBy;
const sort = !!querys.sort && querys.sort;
const dates = !!querys.dates && querys.dates;
const fields = !!querys.fields ? strToArr('fields', 1) : {};
const unFields = !!querys.unFields ? strToArr('unFields', 0) : {};
const dateFn = () => {
if (!!dates) {
const ARR = dates.split(',');
return ARR.length === 2 ? { '$gte': ARR[1], '$lte': ARR[0] } : `${ARR}`
}
}
const sortFn = () => {
let OBJ = {};
if (!!orderBy) {
OBJ[orderBy] = sort;
return OBJ
}
return OBJ || {}
}
delete querys.pages;
delete querys.fields;
delete querys.unFields;
delete querys.orderBy;
delete querys.sort;
delete querys.dates;
return {
'querys': querys || {},
'select': { ...fields, ...unFields },
...(!!pages && {
'pages': {
'marker': pages.split(',')[1] || undefined,
'limit': pages.split(',')[0] || 10
}
}),
...!!orderBy && {
'sort': sortFn()
},
...!!dates && {
'dates': dateFn()
}
}
}
mongo TTL 索引
mongodb • lopo1983 发表了文章 • 0 个评论 • 1549 次浏览 • 2018-10-15 23:48
并且字段类型必须是date类型或者包含有date类型的数组(如果数组中包含多个date类型字段,则取最早时间为过期时间)
官网介绍链接:https://docs.mongodb.com/v3.2/core/index-ttl/
?
①TTL索引是单字段索引,混合索引不支持TTL,并且也会忽略expireAfterSeconds属性②在_id 主键上不能建立TTL索引③在capped collection中不能建立TTL索引,因为MongoDB不能从capped collection中删除文档④你不能使用createIndex()去更改已经存在的TTL索引的expireAfterSeconds值,如果想更改expireAfterSeconds,可以使用collMod命令,否则你只能删除索引,然后重建了⑤你不能在已有索引的字段上再创建TTL索引了,如果你想把非TTL索引改为TTL索引,那就只能删除重建索引了
?
?db.getCollection('smscodes').ensureIndex({'expiresIn':1},{"expireAfterSeconds":60*1})
MongoDB 权威指南的语法 错误 列为:expireAfterSecs 貌似新版的 应该为如上代码 查看全部
并且字段类型必须是date类型或者包含有date类型的数组(如果数组中包含多个date类型字段,则取最早时间为过期时间)
?
- ①TTL索引是单字段索引,混合索引不支持TTL,并且也会忽略expireAfterSeconds属性
- ②在_id 主键上不能建立TTL索引
- ③在capped collection中不能建立TTL索引,因为MongoDB不能从capped collection中删除文档
- ④你不能使用createIndex()去更改已经存在的TTL索引的expireAfterSeconds值,如果想更改expireAfterSeconds,可以使用collMod命令,否则你只能删除索引,然后重建了
- ⑤你不能在已有索引的字段上再创建TTL索引了,如果你想把非TTL索引改为TTL索引,那就只能删除重建索引了
?
?
db.getCollection('smscodes').ensureIndex({'expiresIn':1},{"expireAfterSeconds":60*1})
MongoDB 权威指南的语法 错误 列为:expireAfterSecs 貌似新版的 应该为如上代码
mongo 插入多维数组 唯一 $ne+$push
mongodb • lopo1983 发表了文章 • 0 个评论 • 1545 次浏览 • 2018-09-28 18:22
但是遇到 多维的就会出现问题
?
故只能通过$ne+$push的方式来解决
?
代码如下(egg2.x mongoose5.x)
Schemaconst AllPsListSchema = new Schema({
// 分类中文名称
psName: {
type: String,
required: [true, '服务名称不能为空'],
unique: true,
},
// 分类英文名称
psEnName: {
type: String,
},
// 服务状态 [0/停用,1/正常,2/维护,3/下线]
psState: {
type: Number,
default: 1
},
// 服务子类
psChild: [{
// 产品/服务名称
name: {
type: String,
required: [true, '服务/产品名称不能为空'],
unique: true
},
// 产品/服务英文名称
enName: {
type: String,
required: [true, '服务/产品英文名称不能为空'],
unique: true
},
// 服务状态 [0/停用,1/正常,2/维护,3/下线]
state: {
type: Number,
default: 1
},
// [0/删除,1/锁定,2/正常] 1/锁定意思为不可删除,系统保留
status: {
type: Number,
default: 2
}
}],
// [0:删除,1:锁定,2:正常] 1/锁定意思为不可删除,系统保留
status: {
type: Number,
default: 2
}
}, {
timestamps: {
createdAt: 'created',
updatedAt: 'updated'
}
})
statics
? creatPSChild: async function (_id, bodys) {
const result = await this.findOneAndUpdate({ _id, 'psChild.name': { $ne: bodys.name }, 'psChild.enName': { $ne: bodys.enName } }, {
$push: {
'psChild': bodys
}
});
return { data: result }
} 查看全部
但是遇到 多维的就会出现问题
?
故只能通过$ne+$push的方式来解决
?
代码如下(egg2.x mongoose5.x)
Schema
const AllPsListSchema = new Schema({
// 分类中文名称
psName: {
type: String,
required: [true, '服务名称不能为空'],
unique: true,
},
// 分类英文名称
psEnName: {
type: String,
},
// 服务状态 [0/停用,1/正常,2/维护,3/下线]
psState: {
type: Number,
default: 1
},
// 服务子类
psChild: [{
// 产品/服务名称
name: {
type: String,
required: [true, '服务/产品名称不能为空'],
unique: true
},
// 产品/服务英文名称
enName: {
type: String,
required: [true, '服务/产品英文名称不能为空'],
unique: true
},
// 服务状态 [0/停用,1/正常,2/维护,3/下线]
state: {
type: Number,
default: 1
},
// [0/删除,1/锁定,2/正常] 1/锁定意思为不可删除,系统保留
status: {
type: Number,
default: 2
}
}],
// [0:删除,1:锁定,2:正常] 1/锁定意思为不可删除,系统保留
status: {
type: Number,
default: 2
}
}, {
timestamps: {
createdAt: 'created',
updatedAt: 'updated'
}
})
statics
?
creatPSChild: async function (_id, bodys) {
const result = await this.findOneAndUpdate({ _id, 'psChild.name': { $ne: bodys.name }, 'psChild.enName': { $ne: bodys.enName } }, {
$push: {
'psChild': bodys
}
});
return { data: result }
}
mongodb 备份还原
mongodb • lopo1983 发表了文章 • 0 个评论 • 1489 次浏览 • 2018-09-20 16:58
?mongodump -h dbhost -d dbname -o dbdir
?
上述语法中:-h MongDB所在服务器,可以附带指定端口号‘:port’
-d 需要备份的数据库实例
-o 备份数据存放的位置
如果以上参数都不指定,默认备份127.0.0.1端口号27017的所有数据库到当前的dump目录C:\Program Files\MongoDB\Server\4.0>mongodump
2018-09-20T16:55:53.312+0800 writing admin.system.version to
2018-09-20T16:55:53.356+0800 done dumping admin.system.version (1 document)
2018-09-20T16:55:53.357+0800 writing test.servicebills to
2018-09-20T16:55:53.357+0800 writing test.smslists to
2018-09-20T16:55:53.357+0800 writing test.companylogs to
2018-09-20T16:55:53.357+0800 writing test.smssigns to
2018-09-20T16:55:53.370+0800 done dumping test.companylogs (106 documents)
2018-09-20T16:55:53.370+0800 writing test.companies to
2018-09-20T16:55:53.374+0800 done dumping test.servicebills (347 documents)
2018-09-20T16:55:53.374+0800 writing test.smstemps to
2018-09-20T16:55:53.375+0800 done dumping test.companies (5 documents)
2018-09-20T16:55:53.376+0800 writing test.smsmailcodes to
2018-09-20T16:55:53.385+0800 done dumping test.smstemps (3 documents)
2018-09-20T16:55:53.385+0800 writing test.admins to
2018-09-20T16:55:53.399+0800 done dumping test.smsmailcodes (2 documents)
2018-09-20T16:55:53.399+0800 writing test.users to
2018-09-20T16:55:53.405+0800 done dumping test.admins (1 document)
2018-09-20T16:55:53.405+0800 writing test.complicenses to
2018-09-20T16:55:53.423+0800 done dumping test.users (1 document)
2018-09-20T16:55:53.423+0800 writing test.smscodes to
2018-09-20T16:55:53.429+0800 done dumping test.complicenses (1 document)
2018-09-20T16:55:53.429+0800 writing test.tokens to
2018-09-20T16:55:53.440+0800 done dumping test.smscodes (1 document)
2018-09-20T16:55:53.440+0800 writing test.zones to
2018-09-20T16:55:53.444+0800 done dumping test.zones (0 documents)
2018-09-20T16:55:53.444+0800 writing test.smshistories to
2018-09-20T16:55:53.447+0800 done dumping test.tokens (1 document)
2018-09-20T16:55:53.448+0800 done dumping test.smshistories (0 documents)
2018-09-20T16:55:54.392+0800 done dumping test.smssigns (15 documents)
2018-09-20T16:55:54.402+0800 done dumping test.smslists (202 documents)
?
还原
?mongorestore -h hostname:port -d dbname <path>
?一些重要的参数-h[:port] 指定MongoDB所在的服务器地址,默认为localhost
-d 需要恢复的数据库
--drop 恢复的时候先删除当前数据库,然后恢复备份,慎重操作
<path> 设置备份数据的位置,和下边的参数有冲突
--dir 指定备份的目录,和上边的参数有冲突
?C:\Program Files\MongoDB\Server\4.0>mongorestore -h IP:port --drop --dir ./dump
2018-09-20T16:57:17.847+0800 preparing collections to restore from
2018-09-20T16:57:17.898+0800 reading metadata for test.servicebills from dump\test\servicebills.metadata.json
2018-09-20T16:57:17.898+0800 reading metadata for test.companylogs from dump\test\companylogs.metadata.json
2018-09-20T16:57:17.899+0800 reading metadata for test.smslists from dump\test\smslists.metadata.json
2018-09-20T16:57:17.899+0800 reading metadata for test.smssigns from dump\test\smssigns.metadata.json
2018-09-20T16:57:17.900+0800 restoring test.servicebills from dump\test\servicebills.bson
2018-09-20T16:57:17.900+0800 restoring test.companylogs from dump\test\companylogs.bson
2018-09-20T16:57:17.900+0800 restoring test.smslists from dump\test\smslists.bson
2018-09-20T16:57:17.900+0800 restoring test.smssigns from dump\test\smssigns.bson 查看全部
?
mongodump -h dbhost -d dbname -o dbdir
?
上述语法中:-h MongDB所在服务器,可以附带指定端口号‘:port’
-d 需要备份的数据库实例
-o 备份数据存放的位置
如果以上参数都不指定,默认备份127.0.0.1端口号27017的所有数据库到当前的dump目录
C:\Program Files\MongoDB\Server\4.0>mongodump
2018-09-20T16:55:53.312+0800 writing admin.system.version to
2018-09-20T16:55:53.356+0800 done dumping admin.system.version (1 document)
2018-09-20T16:55:53.357+0800 writing test.servicebills to
2018-09-20T16:55:53.357+0800 writing test.smslists to
2018-09-20T16:55:53.357+0800 writing test.companylogs to
2018-09-20T16:55:53.357+0800 writing test.smssigns to
2018-09-20T16:55:53.370+0800 done dumping test.companylogs (106 documents)
2018-09-20T16:55:53.370+0800 writing test.companies to
2018-09-20T16:55:53.374+0800 done dumping test.servicebills (347 documents)
2018-09-20T16:55:53.374+0800 writing test.smstemps to
2018-09-20T16:55:53.375+0800 done dumping test.companies (5 documents)
2018-09-20T16:55:53.376+0800 writing test.smsmailcodes to
2018-09-20T16:55:53.385+0800 done dumping test.smstemps (3 documents)
2018-09-20T16:55:53.385+0800 writing test.admins to
2018-09-20T16:55:53.399+0800 done dumping test.smsmailcodes (2 documents)
2018-09-20T16:55:53.399+0800 writing test.users to
2018-09-20T16:55:53.405+0800 done dumping test.admins (1 document)
2018-09-20T16:55:53.405+0800 writing test.complicenses to
2018-09-20T16:55:53.423+0800 done dumping test.users (1 document)
2018-09-20T16:55:53.423+0800 writing test.smscodes to
2018-09-20T16:55:53.429+0800 done dumping test.complicenses (1 document)
2018-09-20T16:55:53.429+0800 writing test.tokens to
2018-09-20T16:55:53.440+0800 done dumping test.smscodes (1 document)
2018-09-20T16:55:53.440+0800 writing test.zones to
2018-09-20T16:55:53.444+0800 done dumping test.zones (0 documents)
2018-09-20T16:55:53.444+0800 writing test.smshistories to
2018-09-20T16:55:53.447+0800 done dumping test.tokens (1 document)
2018-09-20T16:55:53.448+0800 done dumping test.smshistories (0 documents)
2018-09-20T16:55:54.392+0800 done dumping test.smssigns (15 documents)
2018-09-20T16:55:54.402+0800 done dumping test.smslists (202 documents)
?
还原
?
mongorestore -h hostname:port -d dbname <path>
?一些重要的参数-h[:port] 指定MongoDB所在的服务器地址,默认为localhost
-d 需要恢复的数据库
--drop 恢复的时候先删除当前数据库,然后恢复备份,慎重操作
<path> 设置备份数据的位置,和下边的参数有冲突
--dir 指定备份的目录,和上边的参数有冲突
?
C:\Program Files\MongoDB\Server\4.0>mongorestore -h IP:port --drop --dir ./dump
2018-09-20T16:57:17.847+0800 preparing collections to restore from
2018-09-20T16:57:17.898+0800 reading metadata for test.servicebills from dump\test\servicebills.metadata.json
2018-09-20T16:57:17.898+0800 reading metadata for test.companylogs from dump\test\companylogs.metadata.json
2018-09-20T16:57:17.899+0800 reading metadata for test.smslists from dump\test\smslists.metadata.json
2018-09-20T16:57:17.899+0800 reading metadata for test.smssigns from dump\test\smssigns.metadata.json
2018-09-20T16:57:17.900+0800 restoring test.servicebills from dump\test\servicebills.bson
2018-09-20T16:57:17.900+0800 restoring test.companylogs from dump\test\companylogs.bson
2018-09-20T16:57:17.900+0800 restoring test.smslists from dump\test\smslists.bson
2018-09-20T16:57:17.900+0800 restoring test.smssigns from dump\test\smssigns.bson
mongodb 数组操作
mongodb • lopo1983 发表了文章 • 0 个评论 • 1543 次浏览 • 2018-09-17 23:00
db.test.update({'_id':id},{
$push:{'arr':{'name':'value'}}
})2.修改
db.test.update({'_id':id,arr.name:'name'},{
$set:{'arr.$.name':'newName'}
})3.删除(多维数组删除)
db.test.update({'_id':id},{
$pull:{arr:{'name':'value'}}
})
? 查看全部
db.test.update({'_id':id},{2.修改
$push:{'arr':{'name':'value'}}
})
db.test.update({'_id':id,arr.name:'name'},{3.删除(多维数组删除)
$set:{'arr.$.name':'newName'}
})
db.test.update({'_id':id},{
$pull:{arr:{'name':'value'}}
})
?
MongoDB 聚合统计
mongodb • lopo1983 发表了文章 • 0 个评论 • 1351 次浏览 • 2018-09-14 14:56
db.集合名称.aggregate({管道:{表达式}})
?管道
?
管道在Unix和Linux中一般用于将当前命令的输出结果作为下一个命令的输入 在mongodb中,管道具有同样的作用,文档处理完毕后,通过管道进行下一次处理 常用管道
$group:将集合中的文档分组,可用于统计结果$match:过滤数据,只输出符合条件的文档$project:修改输入文档的结构,如重命名、增加、删除字段、创建计算结果$sort:将输入文档排序后输出$limit:限制聚合管道返回的文档数$skip:跳过指定数量的文档,并返回余下的文档$unwind:将数组类型的字段进行拆分
?
?
表达式
?
处理输入文档并输出
?
$sum:计算总和?
$avg:计算平均值?
$min:获取最小值?
$max:获取最大值?
$push:在结果文档中插入值到一个数组中?
$first:根据资源文档的排序获取第一个文档数据?
$last:根据资源文档的排序获取最后一个文档数据?
例子
表结构:
const compAccountDealrecordSchema = new Schema({
// billing 订单标识
numer: {
type: String
},
// 公司名称
_comp: {
type: Schema.Types.ObjectId,
ref: 'Company',
required: true,
index: true
},
// 消费金额
amount: {
type: Number,
default: 0.00
},
// 账户余额
balance: {
type: Number,
default: 0.00
},
// 渠道类型
channelType: {
type: String,
default: 'BALANCE'
},
// 日账单
dailyBill: {
type: Boolean,
default: false
},
// 按需扣费账单
debtDeduct: {
type: Boolean,
default: false
},
// 描述
detail: {
type: String,
default: ''
},
// 账单
detailRequest: {
type: Schema.Types.ObjectId,
ref: 'Company',
},
// 账单类型
detailType: {
type: String,
default: 'LINK'
},
// 账单链接
detailUrl: {
type: String,
default: ''
},
// 订单ID
orderId: {
type: Schema.Types.ObjectId,
ref: 'comp_account_billing_order'
},
// 账单产品详细
serviceItem: [],
// 产品类型
serviceType: {},
// 交易类型 [RECHARGE:收入,CONSUME:支出]
transactionType: {
type: String,
default: 'CONSUME'
},
// 备注
remark: {
}
}, {
timestamps: {
createdAt: 'created',
updatedAt: 'updated'
}
});静态方法
compAccountDealrecordSchema.statics = {
getAll: async function(queryMix, _comp) {
const {
querys,
select
} = queryMix;
const models = this.find({
...!!_comp && {
_comp
}
})
.sort({
'_id': -1,
});
try {
return {
data: {
result: await models,
totalCount: await models.count()
}
};
} catch (error) {
return error
}
},
getOne: async function(_id, _comp) {
const MODELS = this.findOne({..._comp && {
_comp
},
_id
}).sort({
'_id': -1
});
try {
return {
data: await MODELS
}
} catch (error) {
return error
}
},
createOne: async function(bodys) {
return await this.create(bodys)
},
backCashAdd: async function(bodys, auth) {
const {
_comp,
serviceBillCash,
serviceBillChannel,
serviceBillRemark
} = bodys
// 生成流水
await this.create({
'_comp': _comp,
'serviceBillProduct': '-',
'serviceBillType': '充值',
'serviceBillCash': `+${serviceBillCash}`,
'serviceBillChannel': `${serviceBillChannel}`,
'serviceBillRemark': `手工入款/n${serviceBillChannel}/n${serviceBillRemark}`,
'_admin': auth.id
});
return await ctx.model.Company.cashFN(serviceBillCash, auth, 'cash', 'add', _comp);
},
seachComp: async function(name) {
return await ctx.model.Company.find({
'compName': eval(`/${name}.*/i`)
}, {
'compEmail': 1,
'compName': 1,
'compPhone': 1
})
},
// 图表数据
/**
*
* @param {*} type 订单类型
* @param {*} scope 月份计算
* @param {*} _comp
*/
getPanelChart: async function(type = 'all', classify = "line", _comp) {
const MODEL = this.aggregate([
...classify === 'pie' ? [{
$unwind: `$serviceItem`,
}] : [],
...[{
$match: {
'_comp': mongoose.Types.ObjectId(_comp),
'created': {
"$gt": new Date(subtractMoment(1, 'month'))
},
"channelType": "CASH",
...type !== 'all' && {
'serviceItem.serviceType': type
}
}
},
{
$project: {
'_comp': 1,
'amount': 1,
'created': 1,
"serviceItem": 1,
'day': {
$substr: ["$created", 0, 10]
}
}
},
{
$group: {
...classify === "line" ? {
'_id': `$day`
} : {
'_id': '$serviceItem.serviceType'
},
'count': {
$sum: classify === 'pie' ? '$serviceItem.price' : '$amount'
}
}
},
{
$project: {
...classify === "line" ? {
'days': '$_id'
} : {
'serviceType': '$_id'
},
'count': 1,
_id: 0
}
},
{
$sort: {
'days': 1
}
}
]
]);
try {
const lastMonth = subtractMoment(1, 'month', 'subtract');
const DateMaps = (getDayAll(lastMonth, new Date()));
const data = await MODEL;
return {
...classify === 'pie' ? {
data
} : {
'data': {
datas: DateMaps.reduce((a, b) => {
let count;
data.forEach(e => {
if (e.days === b) count = e.count
});
a.push(count ? count : 0);
return a
}, []),
dates: DateMaps
}
}
}
} catch (error) {
console.log(error)
}
},
/**
* @param {String} type 产品类型()
*/
getCashCount: async function(ctx, auth, type, _comp) {
const {
endDate
} = ctx.helper.getPrevMoment('month');
const yestoday = ctx.helper.subtractMoment(1, 'day');
const typeoObj = type === 'all' ? {} : {
'serviceBillProduct': type,
'_comp': mongoose.Types.ObjectId(_comp ? _comp : auth.id)
};
return [(await this.aggregate([{
$match: {...typeoObj,
'created': {
"$gt": new Date(endDate)
},
'serviceBillType': '消费'
}
},
{
$group: {
'_id': {
'_comp': auth.id
},
'monthCashSum': {
$sum: "$serviceBillCash"
}
}
},
{
$project: {
'_id': 0
}
}
]))[0], (await this.aggregate([{
$match: {...typeoObj,
'created': {
"$gt": new Date(yestoday)
},
'serviceBillType': '消费'
}
},
{
$group: {
'_id': {
'_comp': auth.id
},
'dayCashSum': {
$sum: "$serviceBillCash"
}
}
},
{
$project: {
'_id': 0
}
},
]))[0]]
},
}; 查看全部
聚合(aggregate)主要用于计算数据,类似sql中的sum(),avg()。
db.集合名称.aggregate({管道:{表达式}})
?管道
?
管道在Unix和Linux中一般用于将当前命令的输出结果作为下一个命令的输入 在mongodb中,管道具有同样的作用,文档处理完毕后,通过管道进行下一次处理 常用管道
- $group:将集合中的文档分组,可用于统计结果
- $match:过滤数据,只输出符合条件的文档
- $project:修改输入文档的结构,如重命名、增加、删除字段、创建计算结果
- $sort:将输入文档排序后输出
- $limit:限制聚合管道返回的文档数
- $skip:跳过指定数量的文档,并返回余下的文档
- $unwind:将数组类型的字段进行拆分
?
?
表达式
?
处理输入文档并输出
?
$sum:计算总和?
$avg:计算平均值?
$min:获取最小值?
$max:获取最大值?
$push:在结果文档中插入值到一个数组中?
$first:根据资源文档的排序获取第一个文档数据?
$last:根据资源文档的排序获取最后一个文档数据?
例子
表结构:
const compAccountDealrecordSchema = new Schema({静态方法
// billing 订单标识
numer: {
type: String
},
// 公司名称
_comp: {
type: Schema.Types.ObjectId,
ref: 'Company',
required: true,
index: true
},
// 消费金额
amount: {
type: Number,
default: 0.00
},
// 账户余额
balance: {
type: Number,
default: 0.00
},
// 渠道类型
channelType: {
type: String,
default: 'BALANCE'
},
// 日账单
dailyBill: {
type: Boolean,
default: false
},
// 按需扣费账单
debtDeduct: {
type: Boolean,
default: false
},
// 描述
detail: {
type: String,
default: ''
},
// 账单
detailRequest: {
type: Schema.Types.ObjectId,
ref: 'Company',
},
// 账单类型
detailType: {
type: String,
default: 'LINK'
},
// 账单链接
detailUrl: {
type: String,
default: ''
},
// 订单ID
orderId: {
type: Schema.Types.ObjectId,
ref: 'comp_account_billing_order'
},
// 账单产品详细
serviceItem: [],
// 产品类型
serviceType: {},
// 交易类型 [RECHARGE:收入,CONSUME:支出]
transactionType: {
type: String,
default: 'CONSUME'
},
// 备注
remark: {
}
}, {
timestamps: {
createdAt: 'created',
updatedAt: 'updated'
}
});
compAccountDealrecordSchema.statics = {
getAll: async function(queryMix, _comp) {
const {
querys,
select
} = queryMix;
const models = this.find({
...!!_comp && {
_comp
}
})
.sort({
'_id': -1,
});
try {
return {
data: {
result: await models,
totalCount: await models.count()
}
};
} catch (error) {
return error
}
},
getOne: async function(_id, _comp) {
const MODELS = this.findOne({..._comp && {
_comp
},
_id
}).sort({
'_id': -1
});
try {
return {
data: await MODELS
}
} catch (error) {
return error
}
},
createOne: async function(bodys) {
return await this.create(bodys)
},
backCashAdd: async function(bodys, auth) {
const {
_comp,
serviceBillCash,
serviceBillChannel,
serviceBillRemark
} = bodys
// 生成流水
await this.create({
'_comp': _comp,
'serviceBillProduct': '-',
'serviceBillType': '充值',
'serviceBillCash': `+${serviceBillCash}`,
'serviceBillChannel': `${serviceBillChannel}`,
'serviceBillRemark': `手工入款/n${serviceBillChannel}/n${serviceBillRemark}`,
'_admin': auth.id
});
return await ctx.model.Company.cashFN(serviceBillCash, auth, 'cash', 'add', _comp);
},
seachComp: async function(name) {
return await ctx.model.Company.find({
'compName': eval(`/${name}.*/i`)
}, {
'compEmail': 1,
'compName': 1,
'compPhone': 1
})
},
// 图表数据
/**
*
* @param {*} type 订单类型
* @param {*} scope 月份计算
* @param {*} _comp
*/
getPanelChart: async function(type = 'all', classify = "line", _comp) {
const MODEL = this.aggregate([
...classify === 'pie' ? [{
$unwind: `$serviceItem`,
}] : [],
...[{
$match: {
'_comp': mongoose.Types.ObjectId(_comp),
'created': {
"$gt": new Date(subtractMoment(1, 'month'))
},
"channelType": "CASH",
...type !== 'all' && {
'serviceItem.serviceType': type
}
}
},
{
$project: {
'_comp': 1,
'amount': 1,
'created': 1,
"serviceItem": 1,
'day': {
$substr: ["$created", 0, 10]
}
}
},
{
$group: {
...classify === "line" ? {
'_id': `$day`
} : {
'_id': '$serviceItem.serviceType'
},
'count': {
$sum: classify === 'pie' ? '$serviceItem.price' : '$amount'
}
}
},
{
$project: {
...classify === "line" ? {
'days': '$_id'
} : {
'serviceType': '$_id'
},
'count': 1,
_id: 0
}
},
{
$sort: {
'days': 1
}
}
]
]);
try {
const lastMonth = subtractMoment(1, 'month', 'subtract');
const DateMaps = (getDayAll(lastMonth, new Date()));
const data = await MODEL;
return {
...classify === 'pie' ? {
data
} : {
'data': {
datas: DateMaps.reduce((a, b) => {
let count;
data.forEach(e => {
if (e.days === b) count = e.count
});
a.push(count ? count : 0);
return a
}, []),
dates: DateMaps
}
}
}
} catch (error) {
console.log(error)
}
},
/**
* @param {String} type 产品类型()
*/
getCashCount: async function(ctx, auth, type, _comp) {
const {
endDate
} = ctx.helper.getPrevMoment('month');
const yestoday = ctx.helper.subtractMoment(1, 'day');
const typeoObj = type === 'all' ? {} : {
'serviceBillProduct': type,
'_comp': mongoose.Types.ObjectId(_comp ? _comp : auth.id)
};
return [(await this.aggregate([{
$match: {...typeoObj,
'created': {
"$gt": new Date(endDate)
},
'serviceBillType': '消费'
}
},
{
$group: {
'_id': {
'_comp': auth.id
},
'monthCashSum': {
$sum: "$serviceBillCash"
}
}
},
{
$project: {
'_id': 0
}
}
]))[0], (await this.aggregate([{
$match: {...typeoObj,
'created': {
"$gt": new Date(yestoday)
},
'serviceBillType': '消费'
}
},
{
$group: {
'_id': {
'_comp': auth.id
},
'dayCashSum': {
$sum: "$serviceBillCash"
}
}
},
{
$project: {
'_id': 0
}
},
]))[0]]
},
};