1、 MongoDB 安装
windows 下安装
- 在官网下载安装文件文件 https://www.mongodb.com/download-center#community
- 将文件安装在D盘(D:\Program Files\MongoDB)或其他盘符下。
- 在D盘下创建文件夹 D:\DATA\MongoDB(任意)
- 配置环境变量;将D:\Program Files\MongoDB\Server\3.0\bin 加入到 path
- 进入cmd, 输入
mongod --dbpath D:\DATA\MongoDB
,出现以下界面,数据库安装成功
Linux下安装
1、 下载数据库文件
curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.0.6.tgz
2、 解压
tar -zxvf mongodb-linux-x86_64-3.0.6.tgz
3、 将文件夹移动至usr
mv mongodb-linux-x86_64-3.0.6/ /usr/local/mongodb
4、MongoDB的数据存储在data目录的db目录下,但是这个目录在安装过程不会自动创建,所以你需要手动创建data目录,并在data目录中创建db目录。
注意:/data/db 是 MongoDB 默认的启动的数据库路径(–dbpath)。
mkdir -p /data/db
注意:如果你的数据库目录不是/data/db,可以通过 –dbpath 来指定。
MongoDB web界面
MongoDB 提供了简单的 HTTP 用户界面。 如果你想启用该功能,需要在启动的时候指定参数 –rest 。
注意:该功能只适用于 MongoDB 3.2 及之前的早期版本。
$ ./mongod --dbpath=/data/db --rest
MongoDB 的 Web 界面访问端口比服务的端口多1000。
如果你的MongoDB运行端口使用默认的27017,你可以在端口号为28017访问web用户界面,即地址为:http://localhost:28017。
2、 MongoDB 指令
进入MongoDB安装目录/bin
- 启动数据库 ./mongod --dbpath=/data/db
- 进入数据库 ./mongo
- show dbs
查看数据库
- use [dbname]
使用数据库,没有数据库时,创建该数据库(如果不进行数据操作则不创建)
- show collections
查看集合
- db.collection.find()
查询集合中的数据 – find({'name':'panlei'})
条件查询
– find().count()
集合总数
– find().skip(3).limit(2).sort({'id':1})
跳过3条,限制2条,根据id排序
- 更新操作
db.collection.update({'id':'1'},{'id':'2'})
更新操作
前面为条件, 默认情况下,后面为全部替换
update({'id':'1'},{$set:{'id':'22'}})
$set 为部分更新
update({'id':'1'},{$set:{'id':'22'}},ture)
有就更新,没有就插入
注意:更新操作默认更新第一条符合条件的记录
更新全部符合条件的数据时:update({'id':'1'},{$set:{'id':'22'}},false,true)
- 删除数据
remove()
方法
db.collection.drop()
删除集合
- 索引
db.collection.getIndexes()
查看集合中索引情况
db.collection.ensureIndex({'name':1})
创建索引 1:正向 2:逆向
db.collection.ensureIndex({'title':1},{'name':'title_index'})
创建索引,并命名
db.collection.dropIndex("title_index")
删除索引
db.collection.ensureIndex({'name':1,'y':1})
复合索引
db.collection.ensureIndex({'name':1},{expireAfterSeconds:10})
过期索引
- 过期索引表示数据在一段时间后过期,数据类型必须为ISODate 或ISODate数组, 该字段的时间过期,表示整条数据都会消失
- 过期时间索引不能是复合索引
- 如果过期时间索引是时间数组,则按照最小时间(最早达成条件)
- 删除时间不是精确的
db.collection.ensureIndex({'name':'text','y':'text'})
创建全文索引
db.collection.ensureIndex({'$**':'text'})
为集合中所有字段添加全文索引
db.collection.find({$text:{$search:'panlei'}})
使用全文索引查询
db.collection.find({$text:{$search:['aa bb cc']}})
或查询
db.collection.find({$text:{$search:['aa bb -cc']}})
不包含cc 的
db.news.find({$text:{$search:"\"wangyan\" \"wangying\""}})
与查询(不可用单引号)
db.collections.find({$text:{$search:"wangyan"}},{"score":{$meta:"textScore"}}).sort({$meta:"textScore"})
根据相似度查询
db.collection.ensureIndex({},{'unique':true})
创建唯一索引
db.collection.ensureIndex({},{'sparse':true})
创建稀疏索引
默认是false, 当不存在key 时也会重建索引
注意: 当强制使用稀疏索引判断key 是否存在时会出现异常数据
比如 db.collection.find({'title':{$exists:false}}).hint("index")