MongoDB 命令

MongoDB 数据库常用命令

  • 连接数据库
1
2
3
4
5
$ mongo --host localhost --port 27017 -u '' -p ''
MongoDB shell version v4.0.10
connecting to: mongodb://localhost:27017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("00722255-7236-47ae-85f4-6c731115fac9")}
MongoDB server version: 4.0.10
  • Help查看命令提示
1
2
3
help
db.help();
db.yourColl.help();
  • 切换/创建数据库
1
2
3
// 当创建一个集合(table)的时候会自动创建当前数据库
use test_mongo_1
switched to db test_mongo_1
  • 查看所有数据库
1
2
3
4
5
6
show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
mongo_test 0.000GB
mongodb 0.000GB
  • 删除当前使用数据库
1
2
3
4
use mongodb;
switched to db mongodb
db.dropDatabase();
{ "dropped" : "mongodb", "ok" : 1 }
  • 从指定主机上克隆数据库
1
db.cloneDatabase("127.0.0.1");
  • 从指定的机器上复制到指定数据库到某个数据库
1
2
3
4
5
6
7
// 将本机的 mongo_test 的数据复制到 mongodb 数据库中
db.copyDatabase("mongo_test", "mongodb", "127.0.0.1");
WARNING: db.copyDatabase is deprecated. See http://dochub.mongodb.org/core/copydb-clone-deprecation
{
"note" : "Support for the copydb command has been deprecated. See http://dochub.mongodb.org/core/copydb-clone-deprecation",
"ok" : 1
}

MongoDB 4.0不推荐使用copydb 和clone命令及其 ~bin.mongo shell帮助程序db.copyDatabase()和 db.cloneDatabase()。

作为替代方案,用户可以使用mongodump和 mongorestore或写入使用驱动程序的脚本。

  • 修复当前数据库
1
2
db.repairDatabase();
{ "ok" : 1 }
  • 显示当前数据库状态
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
db.stats();
{
"db" : "mongodb",
"collections" : 1,
"views" : 0,
"objects" : 3,
"avgObjSize" : 65,
"dataSize" : 195,
"storageSize" : 16384,
"numExtents" : 0,
"indexes" : 1,
"indexSize" : 16384,
"fsUsedSize" : 70578573312,
"fsTotalSize" : 107377324032,
"ok" : 1
}
  • 查看当前使用的数据库
1
2
db.getName();
mongodb
  • 查看当前数据库版本
1
2
db.version();
4.0.10
  • 查看当前数据库的连接服务器地址
1
2
db.getMongo();
connection to localhost:27017
  • 查看/清除 之前的错误信息
1
2
3
4
5
db.getPrevError();
{ "err" : null, "n" : 0, "nPrev" : -1, "ok" : 1 }

db.resetError();
{ "ok" : 1 }

MongoDB Collection 集合

  • 创建一个集合(table)
1
2
db.createCollection("coll_test", {size:20, capped: 5, max: 100});
{ "ok" : 1 }
  • 判断集合是否为定容量
1
2
db.coll_test.isCapped(5);
true
  • 查看指定名称的集合(table)
1
2
db.getCollection("mongo_test");
mongo_test.mongo_test
  • 查看当前db的所有集合
1
2
db.getCollectionNames();
[ "coll_test", "mongo_test" ]
  • 查看当前集合所有集合索引的状态
1
db.printCollectionStats();
  • 查看指定集合的数据条数
1
2
db.mongo_test.count();
3
  • 查看指定集合数据空间大小
1
2
db.mongo_test.dataSize();
195
  • 查看当前集合所在的db
1
2
db.mongo_test.getDB();
mongo_test
  • 查看当前集合的状态
1
2
3
4
5
6
db.coll.stats();
{
"ns" : "mongo_test.coll",
"ok" : 0,
"errmsg" : "Collection [mongo_test.coll] not found."
}
  • 查看指定集合总大小
1
2
db.mongo_test.totalSize();
73728
  • 查看指定集合存储空间大小
1
2
db.mongo_test.storageSize();
36864
  • 集合重命名
1
2
3
4
db.coll_test.renameCollection("mongo_coll");
{ "ok" : 1 }
db.getCollectionNames();
[ "mongo_coll", "mongo_test" ]
  • 删除当前集合
1
2
3
4
5
6
db.getCollectionNames();
[ "mongo_coll", "mongo_test" ]
db.mongo_coll.drop();
true
db.getCollectionNames();
[ "mongo_test" ]

MongoDB 用户相关

  • 创建一个用户
1
2
3
4
5
6
7
8
9
10
11
// 添加用户、设置密码、是否只读
db.createUser({user: 'caoxl', pwd: '110119', roles: [{role: 'readWrite', db: 'mongo_test'}]});
Successfully added user: {
"user" : "caoxl",
"roles" : [
{
"role" : "readWrite",
"db" : "mongo_test"
}
]
}
  • 数据库认证、安全模式登录
1
2
db.auth("caoxl", "110119");
1
  • 显示当前所有用户
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
show users;
{
"_id" : "mongo_test.caoxl",
"userId" : UUID("3ac6d4e3-ef04-45a6-80eb-8bd4b580ba9f"),
"user" : "caoxl",
"db" : "mongo_test",
"roles" : [
{
"role" : "readWrite",
"db" : "mongo_test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
  • 删除用户
1
2
db.dropUser("caoxl");
true

MongoDB 集合查询

  • 查询指定集合所有记录
1
2
3
4
db.mongo_test.find();
{ "_id" : ObjectId("5d71c62e8fb10c51c07d47b1"), "key_1" : "value_1" }
{ "_id" : ObjectId("5d71c7528fb10c51c07d47b3"), "key_2" : "value_2" }
{ "_id" : ObjectId("5d71d685f343000023004253"), "name" : "test_name_1", "info" : "更新后的信息", "updated_at" : ISODate("2019-09-06T03:49:18Z"), "created_at" :ISODate("2019-09-06T03:46:13Z") }

默认每页显示20条记录,当显示不下的情况下,可以用it迭代命令查询下一页数据。注意:键入it命令不能带”;”
但是你可以设置每页显示数据的大小,用DBQuery.shellBatchSize= 50;这样每页就显示50条记录了。

1
2
3
4
5
6
7
8
DBQuery.shellBatchSize=2;
2
db.mongo_test.find();
{ "_id" : ObjectId("5d71c62e8fb10c51c07d47b1"), "key_1" : "value_1" }
{ "_id" : ObjectId("5d71c7528fb10c51c07d47b3"), "key_2" : "value_2" }
Type "it" for more
it
{ "_id" : ObjectId("5d71d685f343000023004253"), "name" : "test_name_1", "info" : "更新后的信息", "updated_at" : ISODate("2019-09-06T03:49:18Z"), "created_at" :ISODate("2019-09-06T03:46:13Z") }
  • 查询去重后的数据
1
2
db.mongo_test.distinct("name");
[ "test_name_1" ]
  • 查看 key_1 = ‘value_1’ 的记录
1
2
db.mongo_test.find({"key_1": "value_1"});
{ "_id" : ObjectId("5d71c62e8fb10c51c07d47b1"), "key_1" : "value_1" }
  • 条件查询
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
MongoDB中条件操作符有:
(>) 大于 – $gt
(<) 小于 – $lt
(>=) 大于等于 – $gte
(<= ) 小于等于 – $lte

db.userInfo.find({age: {$gt: 22}});
// 相当于:select * from userInfo where age>22;

db.userInfo.find({age: {$lt: 22}});
// 相当于:select * from userInfo where age<22;

db.userInfo.find({age: {$gte: 25}});
// 相当于:select * from userInfo where age >= 25;

db.userInfo.find({age: {$lte: 25}});
// 相当于:select * from userInfo where age <= 25;
  • and查询
1
2
3
4
5
db.userInfo.find({age: {$gte: 23, $lte: 26}});
// 相当于:select * from userInfo wher age >=23 and age <=26

db.userInfo.find({name: 'raykaeso', age: 22});
// 相当于:select * from userInfo where name = 'raykaeso' and age = '22′;
  • or查询
1
2
db.userInfo.find({$or: [{age: 22}, {age: 25}]});
// 相当于:select * from userInfo where age = 22 or age = 25;
  • 字符模糊查询
1
2
db.mongo_test.find({name: /test_name/});
{ "_id" : ObjectId("5d71d685f343000023004253"), "name" : "test_name_1", "info" : "更新后的信息", "updated_at" : ISODate("2019-09-06T03:49:18Z"), "created_at" :ISODate("2019-09-06T03:46:13Z") }
  • 查询指定列数据
1
2
3
db.userInfo.find({}, {name: 1, age: 1});
// 相当于:select name, age from userInfo;
// 当然name也可以用true或false
  • 按条件查询指定列数据
1
2
db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});
// 相当于:select name, age from userInfo where age <25;
  • 排序
1
2
升序: db.userInfo.find().sort({age: 1});
降序: db.userInfo.find().sort({age: -1});
  • 查询前n条数据
1
2
3
db.mongo_test.find().limit(2);
{ "_id" : ObjectId("5d71c62e8fb10c51c07d47b1"), "key_1" : "value_1" }
{ "_id" : ObjectId("5d71c7528fb10c51c07d47b3"), "key_2" : "value_2" }
  • 查询n条以后的数据
1
2
db.mongo_test.find().skip(2);
{ "_id" : ObjectId("5d71d685f343000023004253"), "name" : "test_name_1", "info" : "更新后的信息", "updated_at" : ISODate("2019-09-06T03:49:18Z"), "created_at" :ISODate("2019-09-06T03:46:13Z") }
  • 分页查询数据
1
2
3
db.mongo_test.find().limit(2).skip(1);
{ "_id" : ObjectId("5d71c7528fb10c51c07d47b3"), "key_2" : "value_2" }
{ "_id" : ObjectId("5d71d685f343000023004253"), "name" : "test_name_1", "info" : "更新后的信息", "updated_at" : ISODate("2019-09-06T03:49:18Z"), "created_at" :ISODate("2019-09-06T03:46:13Z") }
  • 查询第一条数据
1
2
db.mongo_test.findOne();
{ "_id" : ObjectId("5d71c62e8fb10c51c07d47b1"), "key_1" : "value_1" }
  • 数据求和
1
2
db.mongo_test.find().count();
3

MongoDB 索引

  • 创建索引
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
db.mongo_test.ensureIndex({test_index: 1});
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}

db.mongo_test.ensureIndex({test_index_1: 1, ts: -1});
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}
  • 查看当前集合所有索引
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
db.mongo_test.getIndexes();
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "mongo_test.mongo_test"
},
{
"v" : 2,
"key" : {
"test_index" : 1
},
"name" : "test_index_1",
"ns" : "mongo_test.mongo_test"
},
{
"v" : 2,
"key" : {
"test_index_1" : 1,
"ts" : -1
},
"name" : "test_index_1_1_ts_-1",
"ns" : "mongo_test.mongo_test"
}
]
  • 查看总索引记录大小
1
2
db.mongo_test.totalIndexSize();
69632
  • 查看当前集合的所有索引信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
db.mongo_test.reIndex();
{
"nIndexesWas" : 3,
"nIndexes" : 3,
"indexes" : [
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "mongo_test.mongo_test"
},
{
"v" : 2,
"key" : {
"test_index" : 1
},
"name" : "test_index_1",
"ns" : "mongo_test.mongo_test"
},
{
"v" : 2,
"key" : {
"test_index_1" : 1,
"ts" : -1
},
"name" : "test_index_1_1_ts_-1",
"ns" : "mongo_test.mongo_test"
}
],
"ok" : 1
}
  • 删除指定索引
1
2
db.mongo_test.dropIndex("test_index_1");
{ "nIndexesWas" : 3, "ok" : 1 }
  • 删除所有索引
1
2
3
4
5
6
db.mongo_test.dropIndexes();
{
"nIndexesWas" : 1,
"msg" : "non-_id indexes dropped for collection",
"ok" : 1
}

MongoDB 增删改 集合数据

  • 添加数据
1
2
db.mongo_test.save({name: 'caoxl', age: '25', sex: true});
WriteResult({ "nInserted" : 1 })

添加的数据的数据列,没有固定,根据添加的数据为准

  • 修改数据
1
2
3
4
5
6
7
8
db.mongo_test.find();
{ "_id" : ObjectId("5d7217cca3a236aae02357ca"), "name" : "caoxl", "age" : "25","sex" : true }

db.mongo_test.update({"age": "25"}, {$set: {name: 'changeName'}}, false, true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

db.mongo_test.find();
{ "_id" : ObjectId("5d7217cca3a236aae02357ca"), "name" : "changeName", "age" : "25", "sex" : true }
  • 删除数据
1
2
db.mongo_test.remove({"age": "25"});
WriteResult({ "nRemoved" : 1 })
  • 查询修改删除
1
2
3
4
5
db.mongo_test.findAndModify({
query: {age: {$gte: 25}},
update: {$set: {"name": "caoxl"}, $inc: {"age": 2}},
remove: false
});

其他

Powered by Hexo and Hexo-theme-hiker

Copyright © 2017 - 2023 Keep It Simple And Stupid All Rights Reserved.

访客数 : | 访问量 :