1、下载与安装
下载:https://www.mongodb.com/downloads
安装:直接加压即可。
2、启动
a. 使用 mongo.exe run 启动
b. 在启动时使用 --dbpath 参数指定存储目录,示例:
\bin\mongodb.exe --dbpath d:\data\mongo
c. run 直接启动 ./mongodb run
d. --dbpath 参数指定存储目录启动,若目录不存在则创建,示例:
./mongodb --dbpath /var/data/mongo
e. --port 指定端口启动
./mongod --port 12345
3. 基本概念
MongoDB 由 databases 组成;
databases 由 collections 组成;
collections 由documents (相当于行)组成;
documents 由 fields(相当于列) 组成。
MongoDB 是异步写数据。
4、常用命令
4.1、调用命令
调用命令方法 db.help();
若漏掉 () 则直接显示方法体。
4.2、use
use demodb;
创建 demoedb,不用担心不会创建,当创建第一个 collection 时,demodb 会自动创建。
4.3、插入数据
示例:db.test.insert({"key1":"value1", "key2":"value2"});
插入数据,collection 为 test。
使用 db.getCollectionNames() 可得到 test 和 system.indexes(每个 DB 都有,用于记录 index)。
4.4、查询数据
4.4.1、查询返回 document
db.test.find({"name":"name_value"});
其他说明:
a. $lt、$lte、$gt、$gte、$ne 分别表示小于、小于等于、大于、大于等于、不等于;
b. $exists 用于表示 fields 是否存在;
db.test.find({vampires:{$exists:false}});
c. or 和 and
db.test.find({"gender": "f", "$or": [{${"loves": "apple"}, {"lvoes": "orange"}, {"weight": {$lt:360}}}]});
4.4.2、查询返回 fields
db.test.find(null, {"name": 1});
或
db.test.find({}, {"name": 1});
4.4.3、结果排序
-1 表示降序
db.test.find().sort({"weight":-1});
1 表示升序
db.test.find().sort({"name":1, vampires:-1});
4.4.4、分页查询
db.test.find().sort({weight:-1}).limit(6).skip(6);
4.4.5、查询数量
db.test.count({vampires:{$gt:360}});
或
db.test.find({vampires:{$gt:50}}).count();
4.5、删除数据
db.test.remove();
或
db.test.remove({"name":"test"});
4.6、更新数据(与关系型差异大)
db.test.update({"name": "test"}, {"weight": "360"});
错误语法,此语句是先查询 name 为 "test" 的所有数据,后将符合查询结果所有的 document 一一将其整个document 替换为 {“weight”:360}
正确语法:
db.test.update({"name": "test"}, {"$unset": {"weight": 360}});
4.6.1、增加 filds
db.test.update({"name": "test"}, {"$inc": {"weight": -2}})
$inc 增加或减少数字。
db.test.update({"name": "test"}, {"$push": "{"loves": "sugar"}"});
$push 增加数组元素;
$pop 减少数组元素;
{$pop:{"key":1}} 从数组末尾删除;
{$pop:{"key":-1}} 从数组头部删除;
使用 $addToset 与 $each 组合,一次增加多个不同的值:
db.test.update({"name":"test"}, {"$addToset":{"loves":"{"$each":["apple", "house", "car"]}"}});
4.6.2、upset
若存在则更新,则否添加:
db.test.update({"name": "test"}, {"$inc": {"weight": -2}}, true);
使用第三个参数设置是否 true(upset),默认是 false。
db.test.update({"name": "test"}, {"$inc": {"weight": -2}}, true, false);
使用第四个参数控制是否更新多个,true 则更新多个,false 则更新一个。
4.6.3、批量更新
db.test.update({}, {"gender": "m"});
错误语法,将所有数据的 document 内容都一一替换为了 {"gender": "m"}
正确语法:db.test.update({}, {"$set: {"gender": "m"}"});
4.7、索引
创建:db.test.ensureIndex({"name": "test"});
删除:db.test.dropIndex({"name": 1});
创建独立索引:db.test.ensureIndex({"name": 1, "weight": 1});
5、其他
5.1、使用 web 获取 MongoDB 的信息
http://localhost:28071
5.2、数据备份和恢复
使用 mongodump.exe 备份数据库:
mongodump --db learn --out bakcup
使用 mongorestore.exe 恢复数据库
5.3、导入导出数据
从 JSON 和 CSV 格式导入导出 mongoexport.exe 和 mongoimport.exe:
6、使用 MongoDB
针对关系不是很紧密并且数据量较大的数据,如股票数据。