MongoDB命令

Posted by Sunday on 2018-05-16

帮助

db.help()
db.mycoll.help()
db.mycoll.find().help()

数据库

创建数据库

1
2
> use mydb;
switched to db mydb

删除数据库

1
> db.dropDatabase()

显示所有数据库

1
2
3
4
5
> show dbs;
admin 0.000GB
config 0.000GB
local 0.001GB
testdb 0.001GB

查看数据库属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
> db.stats()
{
"db" : "mydb",
"collections" : 2,
"views" : 0,
"objects" : 14,
"avgObjSize" : 49,
"dataSize" : 686,
"storageSize" : 53248,
"numExtents" : 0,
"indexes" : 3,
"indexSize" : 81920,
"fsUsedSize" : 8654000128,
"fsTotalSize" : 18238930944,
"ok" : 1,
"operationTime" : Timestamp(1526568436, 1),
"$clusterTime" : {
"clusterTime" : Timestamp(1526568436, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}

集合

创建集合,插入数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
> db.mycoll.insert({name:"sunday",age:23})
WriteResult({ "nInserted" : 1 })
> db.mycoll.insert({name:"emma",age:25})
WriteResult({ "nInserted" : 1 })
> db.mycoll.insert({name:"qiaoben",age:30})
WriteResult({ "nInserted" : 1 })

## 插入多行数据
> var res=db.mycoll.insert([{name:"sunday",age:23},{name:"emma",age:24}]);
> res
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]

删除集合

1
2
> db.mycoll.drop()
true

显示所有集合

1
2
3
> show collections;
mycoll
mycoll1
1
2
> db.getCollectionNames()
[ "mycoll", "mycoll1" ]

查看集合属性

1
db.mycoll.stats()

文档

查看文档

1
2
3
4
> db.mycoll.find()
{ "_id" : ObjectId("5afc506a4d12b90251adf8c9"), "name" : "ada", "age" : 24 }
{ "_id" : ObjectId("5afc50724d12b90251adf8ca"), "name" : "emma", "age" : 25 }
{ "_id" : ObjectId("5afc54794d12b90251adf8d7"), "name" : "qiaoben", "age" : 30 }

更新文档

$set 修改指定字段
$unset 删除指定字段
$rename 更改字段名
$inc

1
2
> db.mycoll.update({name:"ada"},{$set:{age:25}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })

删除文档

1
2
db.mycoll.remove({name:"ada"})
WriteResult({ "nRemoved" : 1 })

条件查询

条件操作符

  • $gt 大于
  • $lt 小于
  • $gte 大于等于
  • $lte 小于等于
  • $in 在
  • $nin 不在
1
2
3
4
> db.mycoll.find({age:{$gt:23}})
{ "_id" : ObjectId("5afc506a4d12b90251adf8c9"), "name" : "ada", "age" : 24 }
{ "_id" : ObjectId("5afc50724d12b90251adf8ca"), "name" : "emma", "age" : 25 }
{ "_id" : ObjectId("5afc54794d12b90251adf8d7"), "name" : "qiaoben", "age" : 30 }
1
2
3
> db.mycoll.find({age:{$in:[24,25]}})
{ "_id" : ObjectId("5afc506a4d12b90251adf8c9"), "name" : "ada", "age" : 24 }
{ "_id" : ObjectId("5afc50724d12b90251adf8ca"), "name" : "emma", "age" : 25 }

运算

  • $or 或运算
  • $and 与运算
  • $not 非运算
  • $nor 反运算,返回秒符合的所有文档
  • $exists 是否存在 True,False
  • $mod
  • $type:
    Double,String,Object,Array,Binary data,Undefined,Boolean,Date,Null,Regular Expression,JaveScript,TimeStamp
1
2
3
> db.mycoll.insert({name:"xxx"})
> db.mycoll.find({age: {$exists: false}})
{ "_id" : ObjectId("5afd9500374a6f8ebafbf7cb"), "name" : "xxx" }

查看详细过程

1
db.mycoll.find({name:"sunday"}).explain()

统计

文档总数

1
2
> db.mycoll.count()
2

排序

sort()方法可以通过参数指定排序的字段 1为升序排列,-1是用于降序排列。

1
2
3
> db.mycoll.find().sort({age:-1})
{ "_id" : ObjectId("5afc51a44d12b90251adf8d4"), "name" : "sunday", "age" : 23 }
{ "_id" : ObjectId("5afc506a4d12b90251adf8c9"), "name" : "ada", "age" : 24 }

索引

创建顺序索引

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> db.mycoll.ensureIndex({name:1}
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1,
"operationTime" : Timestamp(1526487310, 1),
"$clusterTime" : {
"clusterTime" : Timestamp(1526487310, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}

查看索引

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
db.mycoll.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "mydb.mycoll"
},
{
"v" : 2,
"key" : {
"name" : 1
},
"name" : "name_1",
"ns" : "mydb.mycoll"
}
]

删除索引

1
2
> db.mycoll.dropIndex("name_1")
{ "nIndexesWas" : 2, "ok" : 1 }

唯一键索引

1
2
3
4
5
6
7
> db.mycoll.ensureIndex({name:1},{unique:true})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}

变量

批量插入测试文档

1
for (i=1;i<=10000;i++) db.stu.insert({name:"student"+i,age:(i%120), address:"#77 TianHe,GuangZhou,Guangdong,China"});

备份与还原

备份

备份全部数据库
mongodump –host 127.0.0.1 –port 27017 –out /data/backup
备份指定数据库
mongodump –host 127.0.0.1 –port 27017 –db mydb –out /data/backup
备份指定集合
mongodump –host 127.0.0.1 –port 27017 –db mydb –collection mycoll –out /data/backup

恢复

恢复全部数据库
mongorestore -h 127.0.0.1 /data/backup/
恢复指定数据库
mongorestore -h 127.0.0.1:27017 -d mydb /data/backup/mydb
恢复指定集合
mongorestore -h 127.0.0.1:27017 -d mydb –collection mycoll /data/backup/mydb/mycoll.bson

监控

mongostat
mongotgop

MongoDB与MySQL命令对比

MySQL MongoDB 说明
mysqld mongod 服务器守护进程
mysql mongo 客户端工具
mysqldump mongodump 逻辑备份工具
mysql mongorestore 逻辑恢复工具
- db.repairDatabase() 修复数据库
mysqldump mongoexport 数据导出工具
source mongoimport 数据导入工具
grant * privileges on . to … Db.addUser()Db.auth() 新建用户并权限
Show databases show dbs 显示库列表
Show tables Show collections 显示表列表
Show slave status rs.status() 查询主从状态
Create table users(a int, b int) db.createCollection(“mycoll”, {capped:true,size:100000}) 创建表,另:可隐式创建表。
Create INDEX idxname ON users(name) db.users.ensureIndex({name:1}) 创建索引
Create INDEX idxname ON users(name,ts DESC) db.users.ensureIndex({name:1,ts:-1}) 创建索引
Insert into users values(1, 1) db.users.insert({a:1, b:1}) 插入记录
Select a, b from users db.users.find({},{a:1, b:1}) 查询表
Select * from users db.users.find() 查询表
Select * from users where age=33 db.users.find({age:33}) 条件查询
Select a, b from users where age=33 db.users.find({age:33},{a:1, b:1}) 条件查询
select * from users where age<33 db.users.find({‘age’:{$lt:33}}) 条件查询
select * from users where age>33 and age<=40 db.users.find({‘age’:{$gt:33,$lte:40}}) 条件查询
select * from users where a=1 and b=’q’ db.users.find({a:1,b:’q’}) 条件查询
select * from users where a=1 or b=2 db.users.find( { $or : [ { a : 1 } , { b : 2 } ] } ) 条件查询
select * from users limit 1 db.users.findOne() 条件查询
select * from users where name like “%Joe%” db.users.find({name:/Joe/}) 模糊查询
select * from users where name like “Joe%” db.users.find({name:/^Joe/}) 模糊查询
select count(1) from users Db.users.count() 获取表记录数
select count(1) from users where age>30 db.users.find({age: {‘$gt’: 30}}).count() 获取表记录数
select DISTINCT last_name from users db.users.distinct(‘last_name’) 去掉重复值
select * from users ORDER BY name db.users.find().sort({name:-1}) 排序
select * from users ORDER BY name DESC db.users.find().sort({name:-1}) 排序
EXPLAIN select * from users where z=3 db.users.find({z:3}).explain() 获取存储路径
update users set a=1 where b=’q’ db.users.update({b:’q’}, {$set:{a:1}}, false, true) 更新记录
update users set a=a+2 where b=’q’ db.users.update({b:’q’}, {$inc:{a:2}}, false, true) 更新记录
delete from users where z=”abc” db.users.remove({z:’abc’}) 删除记录
delete from tb1; db. users.remove() 删除所有的记录
drop database IF EXISTS test; use testdb.dropDatabase() 删除数据库
drop table IF EXISTS test; db.mytable.drop() 删除表/collection
grant xxx db.addUser(‘test’, ’test’) 添加用户readOnly–>false
- db.addUser(‘test’, ’test’, true) 添加用户readOnly–>true
set password for xx@xx = password(‘’); db.addUser(“test”,”test222”) 更改密码
drop user xx@xx; db.system.users.remove({user:”test”})或者db.removeUser(‘test’) 删除用户
root use admin 超级用户
grant db.auth(‘test’, ‘test’) 用户授权
select * from mysql.user db.system.users.find() 查看用户列表
select * from mysql.user show users 查看所有用户
show table status from t; db.printCollectionStats() 查看各collection的状态
show slave status; db.printReplicationInfo() 查看主从复制状态
show profiles; show profile 查看profiling
- db.copyDatabase(‘mail_addr’,’mail_addr_tmp’) 拷贝数据库
查看information_schema db.users.dataSize() 查看collection数据的大小
查看information_schema db. users.totalIndexSize() 查询索引的大小

链接:https://www.jianshu.com/p/59918f9b8be8
链接:http://www.runoob.com/mongodb/mongodb-tutorial.html