准备:
官方网站:https://www.mongodb.com
下载地址:https://www.mongodb.com/download-center/community
一、安装
1、下载后安装,一直下一步即可
看下安装目录。默认是C:\Program Files\MongoDB
2、添加系统变量:
计算机--右键属性--左侧高级系统设置--环境变量--环境变量--path--编辑添加
C:\Program Files\MongoDB\Server\3.4\bin
3、此时打开命令行,输入mongo
C:\Windows\System32>mongo
MongoDB shell version v3.4.20
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.20
Server has startup warnings:
2019-03-26T00:17:19.432-0700 I CONTROL [initandlisten]
2019-03-26T00:17:19.432-0700 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-03-26T00:17:19.432-0700 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2019-03-26T00:17:19.433-0700 I CONTROL [initandlisten]
>
出现此图,则说明安装并配置成功
4、新建数据库文件夹(建议放在D盘且路径不要含有中文)比如:D:\mymongodb文件夹
5、开启mongodb服务,命令行输入mongod --dbpath D:\mymongodb
C:\Windows\System32>mongod --dbpath D:\mymongodb
2019-03-26T00:17:18.386-0700 I CONTROL [initandlisten] MongoDB starting : pid=12904 port=27017 dbpa............................
出现此图则说明启动成功(注意:这个命令行不要关闭,作为服务端,否则mongodb也随之关闭)
6、连接mongodb,保持第5步打开的命令行不要关闭,重新打开一个命令行窗口输入mongo 127.0.0.1:27017
二、使用
1、显示数据库
show dbs
2、使用数据库(如果没有则执行insert后会创建数据库)
use post
3、插入数据
db.post.insert({"title":"Post1","author":"Tom"})
4、查询数据库(只列举简单的,其他用法看手册)
db.post.find() //find all
db.post.find({"age":"20"}) //find that age=20
db.post.find({age:{$gt:20}}) //find that age>20
db.post.find({age:{$gte:20}}) //find that age>=20
db.userInfo.find({age: {$gte: 23, $lte: 26}}); //find that age>=23 && age<=26
db.userInfo.find({name: /^p/}); //find that begin with 'p'
db.userInfo.find({name: /mongo/}); //find like mongo
db.userInfo.find().sort({age: 1}); //order inc
db.userInfo.find().sort({age: -1}); //order desc
db.userInfo.find().limit(5); //find 5
db.userInfo.find().count(); //the count
5、修改数据
db.student.update({"name":"小明"},{$set:{"age":16}});
6、删除数据
db.users.remove({age: 32});
7、删除collentions(数据表)
db.user.drop()
8、删除数据库
use abc
db.DropDataBase()