安装并启动Mongodb
#直接使用脚本启动
./mongod -dbpath /data/mongo/ -logpath /data/mongo/mongo.log -logappend -fork -port 27017
#指定配置文件后台启动
./mongod -f /data/mongodb.cnf --fork --auth
mongodb.cnf
dbpath=/data/mongo/data
logpath=/data/mongo/logs/mongo.log
logappend=true
port=27017
客户端连接到指定服务器
./mongo --host=172.25.20.17 --port=27017
基本操作
#查看所有数据库
show dbs
#切换数据库 use
use mydb
#查看集合数量
show collections
#查找一条 findOne
db.operationLog.findOne()
#根据条件查找 find where
db.operationLog.find({'optime':{'$gt':1541005142000}})
#统计集合数量 count
db.operationLog.find().count()
db.operationLog.count()
#插入数据 insert
db.operationLog.insert({"name":"test"})
#跳过N条 skip
db.operationLog.find().skip(1)
#取前N条 limit
db.operationLog.find().limit(2)
#使用skip limit实现分页功能
db.operationLog.find().skip(1).limit(2)
#排序 sort
db.operationLog.find().sort({'createYYmmdd':-1}).limit(2)
#唯一值 distinct
db.operationLog.distinct('createYYmmdd').sort()
聚合函数
1、实现关系型数据库类似select a ,sum(distinct userCode) from table group a order by a的功能
#聚合函数 aggregate(group ,sum,sort)
db.operationLog.aggregate([
{'$group':{'_id':{'createYYmmdd':'$createYYmmdd','type':'$userCode'}}},
{'$group':{'_id':'$_id.createYYmmdd','count':{'$sum':1}}},
{$sort: {"_id":-1}}
])
#加上匹配条件
db.operationLog.aggregate([
{'$match':{'createYYmmdd':{'$gt':'20181101'}}},
{'$group':{'_id':{'createYYmmdd':'$createYYmmdd','type':'$userCode'}}},
{'$group':{'_id':'$_id.createYYmmdd','count':{'$sum':1}}},
{$sort: {"_id":-1}}
])
2、实现group by having count(1)>1的功能
db.getCollection('test').aggregate(
[{$group: { _id: '$UniqueId',count: {$sum: 1 }}},
{$match: { count: {'$gt': 1 }}}],
{ allowDiskUse: true }
)
备注:allowDiskUse解决内存不足的情况
3、日期类型查找与字段筛选与排序
db.getCollection('cust').find({"AccountTag":true,
"ModifyTime" : {'$lt':ISODate("2021-11-15T16:15:59.352+08:00")}
},{CustomerID:1,_id:0,ModifyTime:1}).sort({"ModifyTime":-1})
4、批量更新字段
db.getCollection('cust').update({"JKnowTag":true},{$set:{"JKnowTag":false}},false, true)
第一个参数查询器
第二个参数修改器
第三个参数代表insertOrUpdate,即存在即更新,否则插入该数据
第四个参数是否修改多条记录
备份还原
#备份
./mongodump -h 127.0.0.1 -d test -o bak
#还原
mongorestore -h 127.0.0.1:27017 -d test bak/test/
-d:
需要备份的数据库实例,例如:test
-o:
备份的数据存放位置,例如:bak