Mongodb常用命令

Mongodb常用命令

Mongodb控制台支持Tab键自动补全代码和提示,这个很方便。

启动和登录
// 启动mongod
mongod --dbpath=/data/mongodbdata --logpath=/data/logs/mongodb.log --logappend &
// 启动mongod,带用户验证
mongod --dbpath=/data/mongodbdata --logpath=/data/logs/mongodb.log --auth --logappend &
// 登录
mongo --host 127.0.0.1 --port 27017 -u admin -p 123456 --authenticationDatabase admin

数据库
// 查看数据库
show dbs;
OR
show databases;
// 创建数据库
use test_db;
// 删除数据库
use test_db;
db.dropDatabase();

集合
// 查看集合
use test_db;
show collections;
OR
show tables;
// 创建集合
db.createCollection(“test_collection”);
OR
直接 insert 数据,系统会自动创建
db.test_collection.insert({field1:100});
// 删除集合
db.test_collection.drop();

索引
// 查看集合索引
db.test_collection.getIndexes();
// 创建索引
db.test_collection.ensureIndex({field1:1});
// 创建唯一索引
db.test_collection.ensureIndex({“field1”:1},{unique:true});
// 删除索引
db.test_collection.dropIndex({“field1”:1});
// 删除全部索引
db.test_collection.dropIndexes();

CRUD
// 增
db.test_collection.insert({“field1”:1,“field2”:2});
// 删
db.test_collection.remove({“field1”:1});
// 改
db.test_collection.update({“field1”:1},{ $set:{“field2”:22}});
db.test_collection.updateMany({},{ $set:{“field2”:22}}); // 更新all
db.test_collection.update({“field1”:1},{ $set:{“field2”:22}},{upsert:true,multi:true}); // upsert: 没有则创建,multi:全部
注意一定要用 $set 指定字段,否则会替换全部字段。
// 查

db.test_collection.find(); // 查找全部记录
db.test_collection.find({"field1":1}); // 查找 field1==1 的记录
db.test_collection.find({"field1":{ "$lt":2,"$gt":0 }}); // 查找field1>0 and field1<2的记录
$lt(<), $lte(<=), $gt(大于), $gte(>=),$ne(!=)
db.test_collection.find({"field1":{ "$in":[1,2,5]}}); // t-sql中的in用法
$nin相当于t-sql中的"not in"
db.test_collection.find({"$or":[{ "field1":1 },{ "field1":3 }]}); // t-sql中的or用法
db.test_collection.find( {"field1" : /word/ } ); // 正则表达式匹配
db.test_collection.find().limit(3).skip(3); // t-sql中的limit 3,3
db.test_collection.find().sort({uid:1}); // 字段uid按升序排序,-1是降序

备份和恢复
// 备份数据库
mongodump -h 127.0.0.1:27017 -u admin -p 123456 -d test_db -o /data/backup/mongodbs
// 恢复数据库
use test_db;
db.dropDatabase();
mongorestore -h 127.0.0.1:27017 -u admin -p 123456 -d test_db --dir /data/backup/mongodbs/test_db/

// 导出集合
mongoexport -h 127.0.0.1:27017 -u admin -p 123456 -d test_db -c test_col -o ./test_col.json
// 导入集合
mongoimport -h 127.0.0.1:27017 -u admin -p 123456 -d test_db -c test_col --file ./test_col.json

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值