MongoDB

Mongodb 的document  16M   Memcached 的value  1M   Redis 的value  512M
ACID  :(Atomicity) 原子性 、 (Consistency) 一致性、 (Isolation) 独立性、 (Durability) 持久性
CAP:一致性(Consistency)、可用性(Availability)、分区容错性(Partition tolerance)
SQL术语		MongoDB术语	解释/说明
database 		database 	数据库
table 		collection 	数据库表/集合
row 		document 	数据记录行/文档
column 		field 		数据字段/域
index 		index 		索引
joins 	  	lookup		表连接
primary key 	primary key 	主键,MongoDB自动将_id字段设置为主键

collection:
db.createCollection(<name>, { capped: <boolean>,
                              autoIndexId: <boolean>,
                              size: <number>,//是整个集合空间大小,单位为【KB】
                              max: <number>,//是集合文档个数上线,单位是【个】
                              storageEngine: <document>,
                              validator: <document>,
                              validationLevel: <string>,
                              validationAction: <string>,
                              indexOptionDefaults: <document> } )
两个参数上限判断取的是【与】的逻辑
如果空间大小到达上限,则插入下一个文档时,会覆盖第一个文档;
如果文档个数到达上限,同样插入下一个文档时,会覆盖第一个文档;


ObjectId
ObjectId("5789fb58631178e7844d11d8")   生成规则
4byte:  5789fb58   =>   时间 1468660568   2016-07-16 17:16:08   
3byte:   631178     =>   机器的唯一标识码
2byte:  e784       =>   进程ID
3byte:  4d11d8     =>   随机数


JSON:
数字(整数或浮点数) 
字符串(在双引号中) 
逻辑值(true 或 false)
数组(在方括号中) 
对象(在花括号中) 
null


BSON:
类型 		    对应数字 	别名 		    
Double 			1 	double 	 {“x”:3} 默认使用浮点型数值
String 			2 	string 	 {“x”:“呵呵”}
Object 			3 	object 	 {“x”:{“y”:3 }}
Array 			4 	array 	 {“x”: [“a“,“b”,”c”]}
Binary data 		5 	binData 	 
Undefined 			6 	undefined 弃用
ObjectId 			7 	objectId  {“x”: objectId()}
Boolean 			8 	“bool” 	  {“x”:true} 
Date 			9 	“date” 	  {“x”:new Date()}
Null 			10 	“null” 	  {“x”:null}
Regular Expression 	11 	“regex”   {“x”:/[abc]/}
DBPointer 			12 	“dbPointer” 	 
JavaScript 		13 	“javascript” {“x”:function(){/*…*/}} 
Symbol 			14 	“symbol” 	 
JavaScript(with scope) 	15 	“javascriptWithScope” 	 
32-bit integer 		16 	“int” 	 {“x”:NumberInt(“3”)}
Timestamp 			17 	“timestamp” 	 	
64-bit integer 		18 	“long” 	 {“x”:NumberLong(“3”)}
Min key 			-1 	“minKey” 	 
Max key 			127 	“maxKey”


Shell:
var mongo=new Mongo("10.4.82.150:27017");
var db=mongo.getDB("local");
var collection=db.getCollection("startup_log");
var list= collection.find().toArray();
printjson(list);

var array = {17964:17963}
for(var name in array){
 db.instanceIndex.update(
 {'processKey':{$in:
 ['carInspectDataSecondVersionFlow','carInspectAssetSecondVersionFlow']},
  'index.shopId':NumberInt(name)},
    {$set:{'index.companyId':NumberInt(array[name])}},
     {
      upsert: false,
      multi: true
    }
 );
}

db.taskIndex.aggregate([
{$lookup: { 
    from: "processData", 
    localField: "instanceId", 
    foreignField: "_id",
    as:"work"}
 },
{$match: {
        'processKey': "carInspectAssetSecondVersionFlow",
        'operatorName':"wei.zuo@renren-inc.com",
        'instanceStartTime':{$gte:ISODate('2019-04-15')}
        }
},
{$count:'count'}]).pretty();


CRUD:
Insert,Find[One,Many,Replace],Bulk,Update,Delete[One,Many]

db.collection.insert(
   <document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)

db.col.find({'name':'www'}).sort({'age':1}).limit(4).skip(2).pretty()
sort()方法可以通过参数指定排序的字段
limit()方法来读取指定数量的数据
skip()方法来跳过指定数量的数据
pretty()方法以格式化的方式来显示所有文档

db.collection.update(
   <filter>,//find()
   <update>,//$set, $unset, or $rename
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ]
   }
)
# 输出信息
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })   

db.collection.delete(
   <filter>,
   {
      writeConcern: <document>,
      collation: <document>
   }
)
remove() 方法已经过时了,现在官方推荐使用 deleteOne() 和 deleteMany() 方法
remove() 方法 并不会真正释放空间,需要继续执行 db.repairDatabase() 来回收磁盘空间



比较运算符
$eq                    =        { <field>: { $eq: <value> } }
$gt   (greater than )  > 
$gte                   >=  
$lt   (less than)      <        {<field> : {$lt :200, $gt :100} }
$lte                   <= 
$ne   (not equal)      !=
$in                    in       { <field>: { $in:["A","E"]} }
$nin  (not in)         !in

逻辑运算符  
$or     $or: [ { <expression1> }, { <expression2> } , { <expressionN> }]
$and
$not
$nor
$exists   { field: { $exists: <boolean> } }
$type     { field: { $type: <BSON type number> | <String alias> } }
db.col.find({"title" : {$type : 2}})  //{"title" : {$type : 'string'}}

评估运算符
$mod       { field: { $mod: [ divisor, remainder ] } }
$regex     { <field>: { $regex: /pattern/, $options: '<options>' } }
$text
$where     { $where: function() {........} }
$all       { <field>: { $all: [ <value1> , <value2> ... ] } }
$elemMatch
$size      { field: { $size: 2 } }
$expr      { $expr: { <expression> } }

update运算符 
$inc,$mul,$rename,$setOnInsert,$set,$unset,$min,$max,$currentDate

数组操作运算符
$addToSet,$pop,$pull,$pullAll,$pushAll,$push,$each,
$slice,$sort,$position,$bit
limit 




aggregation
aggregation:可以多机器跨越查询
语法:db.collection.aggregate(pipeline, options)
pipeline
$project      select
$match        where
$limit        limit
$skip     
$unwind       将数据拆解成每一个document
$group        分组计算
$sample       随机选择文档
$sort         desc asc
$geoNear     经纬度
$lookup      join操作
$out         将最后的结果输出到指定的collection中去 
$indexStats  查询过程中的索引情况
$redact:     决定内嵌文档是否keep

options
allowDiskUse:group和sort都有内存100M的限制,如果为true,就没有100M的限制了

example
db.orders.aggregate([
    {$lookup:{
          from: "inventory",
          localField: "item",
          foreignField: "sku",
          as: "inventory_docs"
          }
   },   
   {   $match:{"price":{$gt:0}}  },
   {
       $group:{"_id":"$item",
               "totalprice":{$sum:"$price"},
               "quantityAvg":{$avg:"$quantity"}
               }
   },
   {   $project:{"_id":1,"totalprice":1}  },
   {   $limit:1  },
   {  $out:"myaggregate"  }], {"allowDiskUse":true}  )
    


gropu:
不可以多机器跨越查询,同时还有100m的限制
example
db.runCommand(
   {group:
       { ns: 'inventory',            //集合
         //key: { "description":1 },   //分组的key
         $keyf:function(doc){
             return {"description":1}      //doc: 当前的文档
          },
         cond: { "_id":{$gt:1} },    //where条件
         $reduce: function (curr, result) {//聚合进行中的每个操作
            //curr:   当前得到的document
            //result: 第一次就是我们目前的initial
                   result.count++;
            return result.total+=curr.instock;
         },
         initial: {"total":0,"count":0 },//聚合的初始文档
         finalize:function(result){      //在某一个groupkey结束后插入点
            result.avg=result.total/result.count;
         }
       }
   }
)



mapReduce:
db.runCommand(
               {
                 mapReduce: <collection>,
                 map: <function>,
                 reduce: <function>,
                 finalize: <function>,
                 out: <output>,
                 query: <document>,
                 sort: <document>,
                 limit: <number>,
                 scope: <document>,
                 jsMode: <boolean>,
                 verbose: <boolean>,
                 bypassDocumentValidation: <boolean>
               }
             )
example
var map=function() {emit(this.description,this.instock);  };
var reduce=function(key,values){return {"values":values};};
var myfinallize=function(key, reducedValue) {
    reducedValue.avg=reducedValue.values && reducedValue.values.length;
    return reducedValue;
}
db.runCommand({
                 mapReduce: "inventory",
                 map: map,
                 reduce: reduce,
                 finalize:myfinallize,
                 out: {inline:1}                 
               }
             )  
 result            
 "counts" : {
        "input" : 6,   //输入了6个文档
        "emit" : 6,    //映射了6个
        "reduce" : 2,  //reduce执行了2次
        "output" : 4   //最终输出是4个。
    }                      


Index索引:
Single Field     单键索引
Compound Index   复合索引
Multikey Index   多键值索引
Geospatial Index 地理索引
Text Indexes     全文索引 
Hashed Indexes   hash索引  O(1)的查找
Unique Indexes   唯一索引
Sparse Indexes   稀疏索引  
TTL  Indexes     过期索引

db.collection.createIndex(keys, options)  //创建索引
db.collection.getIndexes()                //查看集合索引
db.collection.totalIndexSize()            //查看集合索引大小
db.collection.dropIndexes()               //删除集合所有索引
db.collection.dropIndex("indexName")     //删除集合指定索引

options
background	建索引过程会阻塞其它数据库操作,background可指定以后台方式创建索引, 默认值为false。
unique	建立的索引是否唯一。指定为true创建唯一索引。默认值为false.
name	索引的名称。如果未指定,MongoDB的通过连接索引的字段名和排序顺序生成一个索引名称。
dropDups	在建立唯一索引时是否删除重复记录,指定 true 创建唯一索引。默认值为 false. 3.0+版本已废弃
sparse	对文档中不存在的字段数据不启用索引。默认值为 false.
expireAfterSeconds	指定一个以秒为单位的数值,完成 TTL设定,设定集合的生存时间。
v	        索引的版本号。默认的索引版本取决于mongod创建索引时运行的版本。
weights	引权重值,数值在 1 到 99,999 之间,表示该索引相对于其他索引字段的得分权重。
default_language	对于文本索引,该参数决定了停用词及词干和词器的规则的列表。 默认为英语
language_override	对于文本索引,该参数指定了包含在文档中的字段名,默认值为 language.

db.col.createIndex({"title":1,"desc":-1}) //复合索引 1指定按升序创建索引


存储引擎:
wiredtiger
1. Document Level Concurrency  文档级别的并发
2. Snapshots and Checkpoints   快照和(生成快照点) 
   checkpoint: 触发时机:  60s triiger, up to 2G
3. journal: 记录“checkpoint” 和 “checkpoint”的日志记录。
4. compression: wiredtiger会对collection,indexes进行压缩
5. memory use:wiretiger: internal,memorys 

mmapv1  内存文件隐射
In the default configuration for the MMAPv1 storage engine,
MongoDB writes to the data files on disk every 60 seconds 
and writes to the journal files roughly every 100 milliseconds。

in-memory enterpirse 基于内存的存储引擎
指定的方式:--storageEngine
设置占用的内容上限  --inMemorySizeGB



集群:
 master-slave  主从集群
slave会一直读取master的oplog.$main
slave中有一个sources集合,这个集合保存了master的信息
主从有一个10s的延迟

 replica set   副本集  【冗余性和高可用】
1. 初始化集群        rs.initiate() 
2. 查看集群的配置    rs.conf()  
3. 集群中添加members
rs.add("192.168.161.138:27001")
rs.add("192.168.161.138:27002")
rs.status()
rs.addArb("192.168.161.138:27003")   

{
    "set" : "ctrip",
    "date" : ISODate("2016-07-26T22:13:11.565+08:00"),
    "myState" : 1,
    "term" : NumberLong(1),
    "heartbeatIntervalMillis" : NumberLong(2000),
    "members" : [ 
        {
            "_id" : 0,
            "name" : "192.168.161.138:27000",
            "health" : 1.0,
            "state" : 1,
            "stateStr" : "PRIMARY",
            "uptime" : 376,
            "optime" : {
                "ts" : Timestamp(6311636496545742, 1),
                "t" : NumberLong(1)
            },
            "optimeDate" : ISODate("2016-07-26T22:13:08.000+08:00"),
            "electionTime" : Timestamp(6311635401329082, 1),
            "electionDate" : ISODate("2016-07-26T22:08:53.000+08:00"),
            "configVersion" : 4,
            "self" : true
        }, 
        {
            "_id" : 1,
            "name" : "192.168.161.138:27001",
            "health" : 1.0,
            "state" : 2,
            "stateStr" : "SECONDARY",
            "uptime" : 153,
            "optime" : {
                "ts" : Timestamp(6311636496545742, 1),
                "t" : NumberLong(1)
            },
            "optimeDate" : ISODate("2016-07-26T22:13:08.000+08:00"),
            "lastHeartbeat" : ISODate("2016-07-26T22:13:10.546+08:00"),
            "lastHeartbeatRecv" : ISODate("2016-07-26T22:13:08.557+08:00"),
            "pingMs" : NumberLong(0),
            "syncingTo" : "192.168.161.138:27000",
            "configVersion" : 4
        }, 
        {
            "_id" : 2,
            "name" : "192.168.161.138:27002",
            "health" : 1.0,
            "state" : 2,
            "stateStr" : "SECONDARY",
            "uptime" : 153,
            "optime" : {
                "ts" : Timestamp(6311636496545742, 1),
                "t" : NumberLong(1)
            },
            "optimeDate" : ISODate("2016-07-26T22:13:08.000+08:00"),
            "lastHeartbeat" : ISODate("2016-07-26T22:13:10.547+08:00"),
            "lastHeartbeatRecv" : ISODate("2016-07-26T22:13:08.550+08:00"),
            "pingMs" : NumberLong(0),
            "syncingTo" : "192.168.161.138:27000",
            "configVersion" : 4
        }, 
        {
            "_id" : 3,
            "name" : "192.168.161.138:27003",
            "health" : 1.0,
            "state" : 7,
            "stateStr" : "ARBITER",
            "uptime" : 1,
            "lastHeartbeat" : ISODate("2016-07-26T22:13:10.547+08:00"),
            "lastHeartbeatRecv" : ISODate("2016-07-26T22:13:08.562+08:00"),
            "pingMs" : NumberLong(0),
            "syncingTo" : "192.168.161.138:27000",
            "configVersion" : 4
        }
    ],
    "ok" : 1.0
}

sharding   分片  【负载均衡】
开启config服务器
开启mongos服务器
开启shard服务器【mongod进程】
//将mongod进程添加到sharding中
sh.addShard("192.168.161.138:27001")
sh.addShard("192.168.161.138:27002")
//在ctrip这个db上面启动分片功能
sh.enableSharding("ctrip") 
//在ctrip.plane上面开启分片功能,shard key 是 主键ID
sh.shardCollection("ctrip.plane",{"_id":1});

sh.status()
  sharding version: {
	"_id" : 1,
	"minCompatibleVersion" : 5,
	"currentVersion" : 6,
	"clusterId" : ObjectId("5798bcf3105de4fa3269d5c1")
}
  shards:
	{  "_id" : "shard0000",  "host" : "192.168.161.138:27001" }
	{  "_id" : "shard0001",  "host" : "192.168.161.138:27002" }
  active mongoses:
	"3.2.8" : 1
  balancer:
	Currently enabled:  yes
	Currently running:  no
	Failed balancer rounds in last 5 attempts:  0
	Migration Results for the last 24 hours: 
		No recent migrations
  databases:
	{  "_id" : "ctrip",  "primary" : "shard0000",  "partitioned" : true }
		ctrip.plane
			shard key: { "_id" : 1 }
			unique: false
			balancing: true
			chunks:
				shard0000	1
			{ "_id" : { "$minKey" : 1 } } 






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值