1.MongoDB
官网:https://www.mongodb.com/
手册:https://docs.mongodb.org/manual/
win7系统需要安装补丁,KB2731284。
此时,我们看一下装好的文件夹:
C:\ProgramFiles\MongoDB\Server\3.0\bin 加入到系统的path环境变量中
那么我们就能在系统的任何盘符,使用mongo命令了:
mongo 使用数据库
mongod 开机
mongoimport 导入数据
开机命令:C:users\Danny\mongod --dbpath C:\mongo
--dbpath就是选择数据库文档所在的文件夹。
也就是说,mongoDB中,真的有物理文件,对应一个个数据库。U盘可以拷走。
一定要保持,开机这个CMD不能动了,不能关,不能ctrl+c。 一旦这个cmd有问题了,数据库就自动关闭了。
所以,应该再开一个cmd。输入
C:users\Danny\mongo
那么,运行环境就是mongo语法了。
列出所有数据库:
1 show dbs |
使用某个数据库
1 use 数据库名字 |
如果想新建数据库,也是use。use一个不存在的,就是新建。
查看当前所在数据库
1 db |
插入数据:
db.student.insert({"name":"小明","age":16});
student就是所谓的集合。集合中存储着很多json。
student是第一次使用,集合将自动创建。
数据库使用
要管理数据库,必须先开机,开机使用mongod --dbpath c:\mongo
管理数据库:mongo (一定要在新的cmd中输入)
清屏:
1 cls |
查看所有数据库列表
1 show dbs |
使用数据库、创建数据库
1 use itcast |
如果真的想把这个数据库创建成功,那么必须插入一个数据。
数据库中不能直接插入数据,只能往集合(collections)中插入数据。不需要创建集合,只需要写点语法:
1 db.student.insert({“name”:”xiaoming”}); |
db.student 系统发现student是一个陌生的集合名字,所以就自动创建了集合。
删除数据库,删除当前所在的数据库
1 db.dropDatabase(); |
4.1插入数据
插入数据,随着数据的插入,数据库创建成功了,集合也创建成功了。
1 db.student.insert({"name":"xiaoming"}); |
我们不可能一条一条的insert。所以,我们希望用sublime在外部写好数据库的形式,然后导入数据库:
1 mongoimport --db test --collection restaurants --drop --file primer-dataset.json |
-db test 想往哪个数据库里面导入
--collectionrestaurants 想往哪个集合中导入
--drop 把集合清空
--fileprimer-dataset.json 哪个文件
这样,我们就能用sublime创建一个json文件,然后用mongoimport命令导入,这样学习数据库非常方便。
4.2查找数据
查找数据,用find。find中没有参数,那么将列出这个集合的所有文档:
1 db.restaurants.find() |
精确匹配:
1 db.student.find({"score.shuxue":70}); |
多个条件:
1 db.student.find({"score.shuxue":70 , "age":12}) |
大于条件:
1 db.student.find({"score.yuwen":{$gt:50}}); |
或者。寻找所有年龄是9岁,或者11岁的学生
1 db.student.find({$or:[{"age":9},{"age":11}]}); |
查找完毕之后,打点调用sort,表示升降排序。
1 db.restaurants.find().sort( { "borough": 1, "address.zipcode": 1 } ) |
4.3修改数据
修改里面还有查询条件。你要该谁,要告诉mongo。
查找名字叫做小明的,把年龄更改为16岁:
1 db.student.update({"name":"小明"},{$set:{"age":16}}); |
查找数学成绩是70,把年龄更改为33岁:
1 db.student.update({"score.shuxue":70},{$set:{"age":33}}); |
更改所有匹配项目:"
Bydefault, the update() method updates a single document. To update multipledocuments, use the multi option in the update() method.
1 db.student.update({"sex":"男"},{$set:{"age":33}},{multi: true}); |
完整替换,不出现$set关键字了:
1 db.student.update({"name":"小明"},{"name":"大明","age":16}); |
4.4删除数据
1 db.restaurants.remove( { "borough": "Manhattan" } ) |
Bydefault, the remove() method removes all documents that match the remove condition.Use the justOne option to limit the remove operation to only one of thematching documents.
1 db.restaurants.remove( { "borough": "Queens" }, { justOne: true } ) |
Node.js操作MongoDB
需要引包:
1 npm install mongodb |