传统的关系数据库一般由数据库(database)、表(table)、记录(record)三个层次概念组成,MongoDB是由数据库(database)、集合(collection)、文档对象(document)三个层次组成。MongoDB对于关系型数据库里的表,但是集合中没有列、行和关系概念,这体现了模式自由的特点。
mongoDB 常用命令:
database
(1)查看帮助
db.help()
(2)查看当前连接的数据库名称
db.getName()
(3)查看所有数据库名称
show dbs
(4)切换/创建数据库
use mydb
如果mydb数据库不存在,则会自动创建,创建后如果没有往里面建用户,建集合等任何操作,则退出时,会自动删掉。
(5)删掉当前数据库
db.dropDatabase()
(6)修复当前数据库
db.epairDatabase()
(7)查看数据库版本
db.version()
(8)查看当前数据库的连接地址
db.getMongo()
collection
collection,可以理解为mysql或者oracle这些关系数据库中的表(1)创建一个集合(table)
db.createCollection('studnet');
(2)查看所有集合
show cellections
或db.getCollectionNames();
(3)查看所有集合的状态信息
db.printCollectionStats();
(4)删除集合
db.xxx.drop();
xxx就是集合名称,比如db.student.drop()
document
关系型数据库(mysql,oracle等)表中的数据是有许多结构相同(列的类型,个数相同)的行(row)组成的。MongoDB的集合(collection)的数据就是有许多文档(document)组成的,每一个文档不要求一定都类型相同。学习JAVA的同学都知道Map<Key,Value>,那么可以这样理解MongoDB的集合(collection)<_id,文档>._id是特有的,如果你往collection里面插入一个文档,如果不指定_id的值,则系统自动帮你生成。
insert/save
使用insert, 如果不指定_id的值,则相同的文档可以插入任意多个;如果指定了_id的值,如果已存在文档,则报错.
db.student.insert({'name':'貂蝉','age':16}) 成功
db.student.insert({'name':'貂蝉','age':16}) 成功
db.student.insert({'_id':1,'name':'貂蝉','age':16}) 成功
db.student.insert({'_id':1,'name':'甄宓','age':15}) 失败,因为_id=1已存在
db.student.save({'_id':1,'name':'甄宓','age':15}) 成功,新的文档替换掉旧文档,就像JAVA的Map操作一样。
remove
(1)删除所有文档
db.student.remove({});
(2)按条件删除
db.student.remove({'name':'貂蝉'})
update
db.student.update({'name':'貂蝉'},{$set:{'age':18}});
相当于关系型数据库的update student set age = 18 where name = '貂蝉';
query
|
|
|
| db.student.count() | select count(*) from student |
| db.student.find({'name':'貂蝉'}) | select * from student where name = '貂蝉' |
| db.student.find({'name':'貂蝉'}).count() | select count(*) from student where name = '貂蝉' |
| db.student.find({'age':{$lt:20}}); | select * from student where age < 20 |
| db.student.find({'age':{$lte:20}}); | select * from student where age < =20 |
| db.student.find({'age':{$gt:20}}); | select * from student where age > 20 |
| db.student.find({'age':{$gte:20}}); | select * from student where age >= 20 |
| db.student.find({'name':{$in:['貂蝉','甄宓']}}) | select * from student where name in ('貂蝉','甄宓') |
| db.student.find({'name':/尚/}) | select * from student where name like '%尚%' |
| db.student.find({'name':/^孙尚/}) | select * from student where name like '孙尚%' |
| db.student.find({'name':/香^/}) | select * from student where name like '%香' |
| db.student.distinct('name') | select distinct name from student |
| db.student.find().sort({'age':-1}) | select * from student order by age desc |
| db.student.find().sort({'age':1}) | select * from student order by age asc |
| db.student.find().sort({'age':1},{'heigth':-1}) | select * from student order by age asc , heigth desc |
| db.student.findOne() | select * from student limit 1 |
| db.student.find().skip(10).limit(20) | select * from student limit 10,20 |
本文介绍了MongoDB的基础概念,包括数据库、集合、文档等,并详细列举了常用的数据库、集合及文档操作命令,如创建、查询、更新等。
638

被折叠的 条评论
为什么被折叠?



