本文阅读量 次
1. MongoDB 命令行基本使用¶
Mac 下安装
brew install mongosh
1.1 数据库相关¶
1.1.1 查看数据库¶
show dbs
1.1.2 查看当前使用的哪个数据库¶
db
1.1.3 切换当前使用数据库¶
use <db_name>
1.2 Collection 相关¶
1.2.1 添加新的 collection¶
直接通过 collection 名字执行插入语句
db.<new_collection_name>.insert({"name": "12344", age: 18})
1.2.2 重命名 collection¶
db.UUSA.renameCollection("United States of America")
1.3 字段相关¶
1.3.1 新增字段(没有初始值)¶
db.collection.updateMany({}, {$set:{"new_field": null}})
1.3.2 新增字段(设置初始值)¶
db.collection.updateMany({}, {$set:{"new_field": 10}})
初始值来自于其它字段
db.collection.updateMany(
{},
[
{"$set": {"name": { "$concat": ["$field1", " ", "$field2"]}}}
]
)
1.4 查询相关¶
db.myuser.find({...}, {...})
- 第一个是 where 条件
- 第二个是 select xxxx 部分,相当于列名
1.4.1 指定查询排序规则¶
1.4.2 指定结果集返回个数或偏移位置¶
1.4.3 指定结果集都返回哪些字段¶
1.5 索引相关¶
1.5.1 创建索引¶
db.collection.createIndex()
示例
db.collection.createIndex(
{
"a": 1
},
{
unique: true,
sparse: true,
expireAfterSeconds: 3600
}
)
1.5.2 创建多个字段的索引¶
1.5.3 创建索引并指定排序方式¶
1.5.4 按照某个嵌入字段创建索引¶
db.demo.createIndex({"UserDetails.UserPersonalDetails.UserFirstName":1})
1.5.5 创建多个索引¶
db.car.createIndexes([
{ "name": 1 },
{ "cno": 1 },
{ "speed": 1 }
])
1.5.6 获取索引¶
db.<collection>.getIndexes()
1.6 和 MySQL 的对应关系¶
MongoDB | MySQL |
---|---|
db.myuser.find(); | select* from member_audit; |
db.myuser.find({"age": 2}); | select * from myuser where age = 2; |
db.myuser.find({name: 'guo', age: 2}); | select * from myuser where name = ‘guo’ and age = ‘2’; |
db.myuser.find({age: {$gt: 2}}); | select * from myuser where age >2; |
db.myuser.find({age: {$lt: 2}}); | select * from myuser where age <2; |
db.myuser.find({age: {$gte: 2}}); | select * from myuser where age >= 2; |
db.myuser.find({age: {$gte: 2, $lte: 6}}); | select * from myuser where age >= 2 and age <= 6 |
db.myuser.find({memberNo: "2"}); | select * from myuser where name like ‘%2%’; |
db.myuser.find({memberNo: /^E/}); | select * from myuser where memberNo like ‘E%’; |
db.myuser.find({}, {_id: 1, age: 1}); | select id, age from member_audit; |
db.myuser.find({_id: {$gt: 2}}, {id: 1, age: 1}); | select id, age from myuser where id >2; |
db.myuser.find().skip(5); | `` |
db.myuser.find({$or: [{_id: 2}, {mobile: "1"}]}); | select * from myuser where id = 2 or mobile = 1; |
db.myuser.find({auditStatus: 1}).count(); | select count(*) from myuser where age = 20; |
db.myuser.find({auditStatus: {$gte: 1}}).count(); | select count(*) from myuser where age >= 20; |
show dbs | show databases |
show collections | show tables |