常用基本操作
show dbs
db
db.createCollection('要新建的表名')
show collections
db.表名.drop()
db.dropDatabase()
show users
db.dropDatabase()
db.cloneDatabase(“127.0.0.1”)
db.copyDatabase("db", "temp", "127.0.0.1")
db.repairDatabase()
db.getName()
db.stats()
db.version()
db.getMongo()
db.serverStatus().connections.current
db.collection.update({}, {$rename : {"StoreId" : "MetaId"}}, false, true)
db.getCollection("table").find({$where:'this.StoreId.length>2'},{Name:0})
db.getCollection("table").find({}).count()
db.getCollection("collection").find({'StoreId':1139,'CardNo':{'$gte':'90225001','$lte':'90295000'}})
db.getCollection("collection").find({ $or : [{ $and : [{"CardNo" : { $gte : "10000001" }}, {"CardNo" : { $lte : "10000003" }}] }, { $and : [{"CardNo" : { $gte : "10000006" }}, {"CardNo" : { $lte : "10000008" }}] }] }).limit(1000).skip(0)
db.getCollection("collection").find().sort({"CreationTime":1})
db.collection.find({'PicId' : { $type : 16 }}).forEach(function(x) {x.PicId = String(x.PicId);db.table_Experts.save(x);})
db.collection.update({}, {$set: {content:""}}, {multi: true})
db.collection.update({},{$unset:{content:""}},false, true)
db.collection.remove({})
db.news.find( {}, { id: 1, title: 1 } )
db.getCollection('collection').update({},{$rename:{"OId":'MetaId'}},false,true)
db.getCollection('collection').update(
{
"MenuKey" : 28
},
{
$set:{"Url":"..."}
},
false,
true
);
db.collection.aggregate([
{$match: { CreateDate: { $gte: new Date('2018-01-01'), $lte: new Date('2019-07-31') } }} ,
{$group:{_id:{CreateDate:{year: { $year: "$CreateDate"},month: { $month: "$CreateDate" }}}, count: { $sum: 1 }}}
])
db.collection.aggregate([
{
$match: {
CreateDate: {
$gte: new Date('2017-01-01'),
$lte: new Date('2019-07-31')
}
}
},
{
"$group": {
_id: {
month: {
$dateToString: {
format: "%Y-%m",
date: "$CreateDate"
}
}
},
count: {
$sum: 1
}
}
},
{
"$project": {
"年月": "$_id.month",
"总数": "$count",
}
}
])
db.getCollection("collection").find({
CategoryList: {
$all: [
{
"$elemMatch": {
"CategoryId": 'gz',
}
},
{
"$elemMatch": {
"CategoryId": 'g1',
}
},
{
"$elemMatch": {
"CategoryId": 'g1wy',
}
}
]
}
});
db.getCollection("collection").find({
"CardList": {
$elemMatch: {
$and: [{
"CardType": 14
}, {
"Number": {
$gt: 0
}
}]
}
}
})
db.getCollection("collection").find({
CardList: {
$all: [
{
"$elemMatch": {
"CardType": 2,
"Name": "aaa"
}
},
{
"$elemMatch": {
"CardType": 3,
"Name": "bbb"
}
}
]
}
});
db.getCollection("collection").find({
$and: [
{
CardList: {
"$elemMatch": {
"CardType": 2,
"Name": "aaa"
}
}
},
{
CardList: {
"$elemMatch": {
"CardType": 3,
"Name": "bbb"
}
}
}
]
});
db.getCollection("collection").find({
StudentNumId: 1168,
_id: ObjectId('5be29c013a9d283484b7173f'),
'FiveStars': {
$size: 3
}
});
db.getCollection('collection').aggregate([{
"$match": {
"$and": [{
"ParentName": {
"$eq": ""
}
}]
}
}, {
"$group": {
"_id": {
"GroupName": {
$concat: [{
$substr: ["$Year", 0, 4]
}, "-", {
$substr: ["$Month", 0, 2]
}]
}
}
}
}, {
"$project": {
"GroupName": "$_id.GroupName",
"_id": 0
}
}])
db.getCollection("collection").aggregate(
[
{
$match: {
$and: [
{
$and: [{
"IsDeleted": {
$ne: true
}
}, {
"ProvinceId": 859
}]
},
{
$or: [{
$and: [{
"CourseTypeId": 1
}, {
"Total": {
$gte: 400
}
}, {
"Total": {
$lte: 517
}
}]
}, {
$and: [{
"CourseTypeId": 0
}, {
"Total": {
$gte: 363
}
}, {
"Total": {
$lte: 467
}
}]
}]
}
]
}
},
{
$lookup: {
from: "collection2",
localField: "UserId",
foreignField: "NumId",
as: "users"
}
},
{
$project: {
"用户名": {
$arrayElemAt: ['$users.Username', 0]
},
"手机号": {
$arrayElemAt: ['$users.MobilePhone', 0]
},
"真实姓名": {
$arrayElemAt: ['$users.RealName', 0]
},
"Total": 1
}
},
]
);
db.collection.aggregate(
[
{
"$match": {
"$and": [{
"Status": 2
}, {
"Type": 2
}
]
}
},
{
"$group": {
_id: {
month: {
$dateToString: {
format: "%Y-%m",
date: "$Time"
}
}
},
sum: {
$sum: "$Price"
}
}
},
{
"$project": {
"Date": "$_id.month",
"Sum": "$sum",
"_id": 0
}
}
]
)
Collection 聚集集合
db.createCollection("collectionName", {size: 20, capped: 5, max: 100});
db.getCollection("account");
db.getCollectionNames();
db.printCollectionStats();
db.yourColl.help();
db.yourColl.count();
db.userInfo.dataSize();
db.userInfo.getDB();
db.userInfo.stats();
db.userInfo.totalSize();
db.userInfo.storageSize();
db.userInfo.getShardVersion();
db.userInfo.renameCollection("users");
db.userInfo.drop();
数据的增删改查操作
db.表名.insert(数据);
db.test1.insertOne(数据);
db.表名.insert([数据1,数据2]);
db.表名.insertMany([数据1,数据2]);
db.表名.save(数据);
db.表名.remove(条件);
db.表名.deleteOne(条件)
db.表名.deleteMany(条件)
db.表名.update({"条件字段名":"字段值"},{$set:{"要修改的字段名":"修改后的字段值"}});
db.inventory.updateOne(
{ item: "paper" },
{
$set: { "size.uom": "cm", status: "P" },
$currentDate: { lastModified: true }
}
)
db.inventory.updateMany(
{ "qty": { $lt: 50 } },
{
$set: { "size.uom": "in", status: "P" },
$currentDate: { lastModified: true }
}
)
db.inventory.replaceOne(
{ item: "paper" },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
)
db.表名.find()
db.表名.find(条件)
db.表名.findOne(条件)
db.表名.find().limit(数量)
db.表名.find().skip(数量)
db.表名.find().skip(起始数量).limit(显示的数量)
db.serverStatus()详解
PRIMARY > db.serverStatus()
{
"host": "cd9a511a2d0e",
"version": "2.6.1",
,
"process": "mongod",
"pid": NumberLong(41),
"uptime": 3785943,
"uptimeMillis": NumberLong("3785942955"),
"uptimeEstimate": 3755878,
"localTime": ISODate("2015-10-16T02:46:27.368Z"),
"asserts": {
"regular": 0,
"warning": 0,
"msg": 0,
"user": 58,
"rollovers": 0
},
"backgroundFlushing": {
"flushes": 63098,
"total_ms": 144997713,
"average_ms": 2297.97637009097,
"last_ms": 10913,
"last_finished": ISODate("2015-10-16T02:45:40.363Z")
},
"connections": {
"current": 1444,
"available": 18556,
"totalCreated": NumberLong(2429949)
},
"cursors": {
"note": "deprecated, use server status metrics",
"clientCursors_size": 1,
"totalOpen": 1,
"pinned": 0,
"totalNoTimeout": 481,
"timedOut": 84
},
"dur": {
"commits": 27,
"journaledMB": 2.711552,
"writeToDataFilesMB": 5.213888,
"compression": 0.5158220112430492,
"commitsInWriteLock": 0,
"earlyCommits": 0,
"timeMs": {
"dt": 3003,
"prepLogBuffer": 1,
"writeToJournal": 228,
"writeToDataFiles": 10,
"remapPrivateView": 2
}
},
"extra_info": {
"note": "fields vary by platform",
"heap_usage_bytes": 96529464,
"page_faults": 11253067
},
"globalLock": {
"totalTime": NumberLong("3785942955000"),
"lockTime": NumberLong("47441423960"),
"currentQueue": {
"total": 0,
"readers": 0,
"writers": 0
},
"activeClients": {
"total": 0,
"readers": 0,
"writers": 0
}
},
"indexCounters": {
"accesses": 5980339643,
"hits": 5980339322,
"misses": 0,
"resets": 0,
"mi***atio": 0
},
"locks": {
".": {
"timeLockedMicros": {
"R": NumberLong(1300731481),
"W": NumberLong("47441423960")
},
"timeAcquiringMicros": {
"R": NumberLong("83350794378"),
"W": NumberLong("8842280365")
}
},
},
"network": {
"bytesIn": 182494603618,
"bytesOut": NumberLong("2936449550300"),
"numRequests": 600302443
},
"opcounters": {
"insert": 214538892,
"query": 388689,
"update": 3462611,
"delete": 0,
,
"getmore": 188590632,
"command": 197825527
},
"opcountersRepl": {
"insert": 1,
"query": 0,
"update": 0,
"delete": 0,
"getmore": 0,
"command": 0
},
"recordStats": {
"accessesNotInMemory": 8377141,
"pageFaultExceptionsThrown": 2926497,
"admin": {
"accessesNotInMemory": 94,
"pageFaultExceptionsThrown": 0
}
},
"repl": {
"setName": "c562ca6c-1d72-4c6a-a943-b46fe87e47ca",
"setVersion": 105039,
"ismaster": true,
"secondary": false,
"hosts": [
"10.10.1.1:27017",
"10.10.1.2:27017"
],
"arbiters": [
"10.10.1.2:27017"
],
"primary": "10.10.1.4:27017",
"me": "10.10.1.5:27017"
},
"writeBacksQueued": false,
"mem": {
"bits": 64,
"resident": 4430,
"virtual": 813370,
"supported": true,
"mapped": 405498,
"mappedWithJournal": 810996
},
"metrics": {
"cursor": {
"timedOut": NumberLong(84),
"open": {
"noTimeout": NumberLong(481),
"pinned": NumberLong(0),
"total": NumberLong(1)
}
},
"document": {
"deleted": NumberLong(0),
"inserted": NumberLong(214538892),
"returned": NumberLong("6735629965"),
"updated": NumberLong(6502807)
},
"getLastError": {
"wtime": {
"num": 0,
"totalMillis": 0
},
"wtimeouts": NumberLong(0)
},
"operation": {
"fastmod": NumberLong(3483995),
"idhack": NumberLong(39),
"scanAndOrder": NumberLong(6)
},
"queryExecutor": {
"scanned": NumberLong(107218344),
"scannedObjects": NumberLong(107217952)
},
"record": {
"moves": NumberLong(1604)
},
"repl": {
"apply": {
"batches": {
"num": 2,
"totalMillis": 8
},
"ops": NumberLong(1)
},
"buffer": {
"count": NumberLong(0),
"maxSizeBytes": 268435456,
"sizeBytes": NumberLong(0)
},
"network": {
"bytes": NumberLong(709),
"getmores": {
"num": 18,
"totalMillis": 86108
},
"ops": NumberLong(2),
"readersCreated": NumberLong(35)
},
"preload": {
"docs": {
"num": 0,
"totalMillis": 0
},
"indexes": {
"num": 1,
"totalMillis": 0
}
}
},
"storage": {
"freelist": {
"search": {
"bucketExhausted": NumberLong(0),
"requests": NumberLong(6551285),
"scanned": NumberLong(12001208)
}
}
},
"ttl": {
"deletedDocuments": NumberLong(0),
"passes": NumberLong(63048)
}
},
"ok": 1
}
权限管理
mongodb 数据库用户角色
read:允许用户读取指定数据库
readWrite:允许用户读写指定数据库
dbAdmin:允许用户进行索引创建、删除,查看统计或访问system.profile,但没有角色和用户管理的权限
userAdmin:提供了在当前数据库中创建和修改角色和用户的能力
dbOwner: 提供对数据库执行任何管理操作的能力。这个角色组合了readWrite、dbAdmin和userAdmin角色授予的特权。
clusterAdmin : 提供最强大的集群管理访问。组合clusterManager、clusterMonitor和hostManager角色的能力。还提供了dropDatabase操作
clusterManager : 在集群上提供管理和监视操作。可以访问配置和本地数据库,这些数据库分别用于分片和复制
clusterMonitor : 提供对监控工具的只读访问,例如MongoDB云管理器和Ops管理器监控代理。
hostManager : 提供监视和管理服务器的能力。
backup : 提供备份数据所需的能力,使用MongoDB云管理器备份代理、Ops管理器备份代理或使用mongodump
restore : 提供使用mongorestore恢复数据所需的能力
readAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读权限
readWriteAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读写权限
userAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的userAdmin权限
dbAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的dbAdmin权限。
root:提供对readWriteAnyDatabase、dbAdminAnyDatabase、userAdminAnyDatabase、clusterAdmin、restore和backup的所有资源的访问
创建用户
use admin
db.createUser({
user:"admin",
pwd:"123456",
roles:[{
role:"root",
db:"admin"
}]
})
use testDB
db.createUser({user:'test',pwd:'123456',roles:[{role:'readWrite',db:'testDB'}]})
db.updateUser('test',{user:'test',pwd:'admin',roles:[{role:'read',db:'testDB'}]}) //修改密码 并且 //修改角色为只读
常用的用户命令
db.addUser("name");
db.addUser("userName", "pwd123", true); 添加用户、设置密码、是否只读
db.auth("userName", "123123");
show users;
db.removeUser("test")
索引
db.userInfo.ensureIndex({name: 1});
db.userInfo.ensureIndex({name: 1, ts: -1});
db.userInfo.getIndexes();
db.userInfo.totalIndexSize();
db.users.reIndex();
db.users.dropIndex("index_name");
db.users.dropIndexes();