Mongo之安装
Centos
1.下载安装包
远程安装mongodb压缩包
1 | wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.4.9.tgz |
2.解压缩安装包
在/opt下创建modules文件夹
1 | mkdir modules |
然后解压到这里:
1 | cd ~ |
进入modules文件夹
1 | cd /opt/modules/ |
重命名为mongodb
1 | mv mongodb-linux-x86_64-3.4.9 mongodb |
3.创建数据库存放目录和日志存放目录
将服务的数据存放在/opt/data目录下,需要创建db目录用于存放数据库文件,logs目录存放日志文件:
1 | mkdir -p /opt/data/mongodb/data |
4.创建MongoDB配置文件mongodb.conf
mongodb.conf主要配置MongoDB的监听端口,数据库目录,日志存放位置,日志输出方式以及是否开启后台运行等:
1 | cd /opt/data/mongodb/data/ |
mongodb.conf 具体配置信息如下:
1 | # 端口号 |
5.启动MongoDB服务
执行以下命令启动MongoDB服务:
1 | cd /opt/modules/mongodb/ |
会打印下面信息:about to fork child process, waiting until server is ready for connections. forked process: 20913 child process started successfully, parent exiting
6.验证MongoDB服务是否启动成功
1 | lsof -i:27017 |
成功打印COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME mongod 20913 root 7u IPv4 376964 0t0 TCP *:27017 (LISTEN) 可以通过ip访问,http://你的公网ip:28017/, 显示数据库一些信息,说明启动成功了 It looks like you are trying to access MongoDB over HTTP on the native driver port.
ubuntu环境
步骤
Update Homebrew’s package database. In a system shell ,issue the following command:
brew update
Install MongoDB. You can install MongoDB via brew with several different options.Use one of the following operations:
Install the MongoDB binaries To install the MongoDB binaries ,issue the following command in system shell:
brew install mongodb
Install the MongoDB Binaries with TLS/SSL Support To install the MongoDB binaries that have TLS/SSL suport ,issue the following from a system shell:
brew install mongodb –with-openssl
Install the Lastest Development Release of MongoDB To install the lastest development release for use in testing and development,issue the following command in a system shell:
brew install mongodb –devel
Install MongoDB Community Edition Manually. Only install MongoDB Community Edition using this procedure if you cannot use homebrew.
- Download the binary files for the desired release of MongoDB
Download the binaries from https://www.mongodb.org/downloads. For example, to download the latest release through the shell, issue the following:
curl -O https://fastdl.mongodb.org/osx/mongodb-osx-x86_64-3.2.6.tgz
- Extract the files from the downloaded archive.
For example, from a system shell, you can extract through the tar command:
tar -zxvf mongodb-osx-x86_64-3.2.6.tgz
- Copy the extracted archive to the target directo
Copy the extracted folder to the location from which MongoDB will run.
mkdir -p mongodb
cp -R -n mongodb-osx-x86_64-3.2.6/ mongodb
- Ensure the location of the binaries is in the PATH variable.
The MongoDB binaries are in the bin/ directory of the archive. To ensure that the binaries are in your PATH, you can modify your PATH. For example, you can add the following line to your shell’s rc file (e.g. ~/.bashrc):
export PATH=
/bin:$PATH
- Download the binary files for the desired release of MongoDB
Replace
brew 安装结果
1 | brew install mongodb |
Run MongoDB
1.Create the data directory Before you start MongoDB for the first time ,create the directory to which the mongod process will write data.By default ,the mongod process uses the /data/db/directory.If you create a directory other than this one ,you must specify that directory in the dbpath option when starting the mongod proecss later in this peocedure. The following example command creates the default /data/db directory:
1 | mkdir -p /data/db |
2.Set permissions for the data direcory. Before running mongod for the first time,ensure that the user account running mongod has read and write permissions for the directory. 3.Run MongoDB. To run MongoDB,run the mongod process at the system prompt.If necessary,specify the path the mongod or the data directory.See the following examples.
Run without specifying paths If your system Path variable includes the location of the mongod binary and if you use the default data directory(i.e.,/data/db),simply enter mongod at the system prompt:
1
mongod
Specify the path of the mongod If your PATH does not include the location of the mongod binary,enter the full path to the mongod binary at the system prompt:
1
<path to binary>/mongod
Specify the path of the data directory If you do not use the defautl data directory (i.i.,/data/db),specify the path to the data directory using the –dbpath option:
1
mongod --dbpath <path to data directory>
Begin using MongoDB. mongod 默认数据保存路径:/data/db/ 默认端口:27017 修改默认路径:–dbpath 修改默认端口:–port 启动后台服务:–fork(必须使用–logpath自动创建日志输出目录)
注意事项
1.启动
- mongod 启动mongo服务
- mongo 启动客户端
2.停止服务
方法一 ps -ef | grep mongodb 找到你要查找的进程号 kill - 2 pid 杀掉
方法二 进入mongo数据库里面进行操作
1
2
3mongo
use admin
db.shutdownServer();错误 在linux下大家停止很多服务喜欢直接kill -9 PID,但是对于MongoDB如果执行了kill - 9 PID,在下次启动时可能提示错误,导致服务无法启动,这个时候可以通过执行:rm -f path/db/mongod.lock,也即删除指定数据目录下的mongod.lock问价即可.
错误
I’ve just installed MOngoDB via homebrew und want to start it via command line mongod.
When I do that, i’ll get this message:
1 | 2016-03-05T19:23:55.763+0100 I CONTROL [initandlisten] MongoDB starting : pid=52426 port=27017 dbpath=/data/db 64-bit host=Matthias-MBP |
The last line doesn’t sound correct. What is the problem? The first line of logs says
1 | MongoDB starting : pid=52426 port=27017 dbpath=/data/db 64-bit host=Matthias-MBP". |
Notice that host name is Matthias-MBP, so you can add 127.0.0.1 Matthias-MBP in /etc/hosts file. After Ctrl-C and re-run mongod, the error message will disappear.
操作相关
数据库
Help查看命令提示
1
2
3
4
5help
db.help();
db.yourColl.help();
db.youColl.find().help();
rs.help();切换/创建数据库
1
2>use yourDB;
当创建一个集合(table)的时候会自动创建当前数据库查询所有数据库
1
show dbs;
删除当前使用数据库
1
db.dropDatabase();
从指定主机上克隆数据库
1
2db.cloneDatabase(“127.0.0.1”);
将指定机器上的数据库的数据克隆到当前数据库从指定的机器上复制指定数据库数据到某个数据库
1
2db.copyDatabase("mydb", "temp", "127.0.0.1");
将本机的mydb的数据复制到temp数据库中修复当前数据库
1
db.repairDatabase();
查看当前使用的数据库
1
2
3db.getName();
db;
db和getName方法是一样的效果,都可以查询当前使用的数据库显示当前db状态
1
db.stats();
当前db版本
1
db.version();
查看当前db的链接机器地址
1
db.getMongo();
Collection聚集集合
创建一个聚集集合(table)
1
db.createCollection(“collName”, {size: 20, capped: 5, max: 100});
得到指定名称的聚集集合(table)
1
db.getCollection("account");
得到当前db的所有聚集集合
1
db.getCollectionNames();
显示当前db所有聚集索引的状态
1
db.printCollectionStats();
用户相关
- 添加一个用户
1
2db.addUser("name");
db.addUser("userName", "pwd123", true);
添加用户、设置密码、是否只读
数据库认证、安全模式
1
db.auth("userName", "123123");
显示当前所有用户
1
show users;
删除用户
1
db.removeUser("userName");
其他
查询之前的错误信息
1
db.getPrevError();
清除错误记录
1
db.resetError();
Collection聚合集合操作
###查看聚集集合基本信息
查看帮助
1
db.yourColl.help();
查询当前集合的数据条数
1
db.yourColl.count();
查看数据空间大小
1
db.userInfo.dataSize();
得到当前聚集集合所在的db
1
db.userInfo.getDB();
得到当前聚集的状态
1
db.userInfo.stats();
得到聚集集合总大小
1
db.userInfo.totalSize();
聚集集合储存空间大小
1
db.userInfo.storageSize();
Shard版本信息
1
db.userInfo.getShardVersion()
聚集集合重命名
1
db.userInfo.renameCollection("users");
将userInfo重命名为users
- 删除当前聚集集合
1
db.userInfo.drop();
聚集集合查询
- 查询所有记录
1
db.userInfo.find();
相当于:select * from userInfo;
默认每页显示20条记录,当显示不下的情况下,可以用it迭代命令查询下一页数据。注意:键入it命令不能带“;”
但是你可以设置每页显示数据的大小,用DBQuery.shellBatchSize = 50;这样每页就显示50条记录了。
- 查询去掉后的当前聚集集合中的某列的重复数据
1
db.userInfo.distinct("name");
会过滤掉name中的相同数据
相当于:select distict name from userInfo;
查询age = 22的记录
db.userInfo.find({"age": 22});
相当于:select * from userInfo where age = 22;
查询age > 22的记录
db.userInfo.find({age: {$gt: 22}});
相当于:select * from userInfo where age > 22;
查询age < 22的记录
db.userInfo.find({age: {$lt: 22}});
相当于:select * from userInfo where age < 22;
查询age >= 25的记录
db.userInfo.find({age: {$gte: 25}});
相当于:select * from userInfo where age >= 25;
查询age <= 25的记录
db.userInfo.find({age: {$lte: 25}});
查询age >= 23 并且 age <= 26
db.userInfo.find({age: {$gte: 23, $lte: 26}});
查询name中包含 mongo的数据
db.userInfo.find({name: /mongo/});
//相当于%%select * from userInfo where name like ‘%mongo%’;
查询name中以mongo开头的
db.userInfo.find({name: /^mongo/});
select * from userInfo where name like ‘mongo%’;
查询指定列name、age数据
db.userInfo.find({}, {name: 1, age: 1});
相当于:select name, age from userInfo;
当然name也可以用true或false,当用ture的情况下河name:1效果一样,如果用false就是排除name,显示name以外的列信息。
12、查询指定列name、age数据, age > 25
db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});
相当于:select name, age from userInfo where age > 25;
按照年龄排序 升序:
db.userInfo.find().sort({age: 1});
降序:db.userInfo.find().sort({age: -1});
查询name = zhangsan, age = 22的数据
db.userInfo.find({name: 'zhangsan', age: 22});
相当于:select * from userInfo where name = ‘zhangsan’ and age = ‘22’;
查询前5条数据
db.userInfo.find().limit(5);
相当于:select top 5 * from userInfo;
查询10条以后的数据
db.userInfo.find().skip(10);
相当于:select * from userInfo where id not in ( select top 10 * from userInfo );
查询在5-10之间的数据
db.userInfo.find().limit(10).skip(5);
可用于分页,limit是pageSize,skip是第几页*pageSizeor与 查询
db.userInfo.find({$or: [{age: 22}, {age: 25}]});
相当于:select * from userInfo where age = 22 or age = 25;
查询第一条数据
db.userInfo.findOne();
相当于:select top 1 * from userInfo; db.userInfo.find().limit(1);
查询某个结果集的记录条数
db.userInfo.find({age: {$gte: 25}}).count();
相当于:select count(*) from userInfo where age >= 20;
按照某列进行排序
db.userInfo.find({sex: {$exists: true}}).count();
相当于:select count(sex) from userInfo;
索引
创建索引
1
2db.userInfo.ensureIndex({name: 1});
db.userInfo.ensureIndex({name: 1, ts: -1});查询当前聚集集合所有索引
db.userInfo.getIndexes();
查看总索引记录大小
db.userInfo.totalIndexSize();
读取当前集合的所有index信息
db.users.reIndex();
删除指定索引
db.users.dropIndex("name_1");
删除所有索引索引
db.users.dropIndexes();
修改、添加、删除集合数据
添加
db.users.save({name: ‘zhangsan’, age: 25, sex: true});
添加的数据的数据列,没有固定,根据添加的数据为准修改
db.users.update({age: 25}, {$set: {name: 'changeName'}}, false, true);
相当于:update users set name = ‘changeName’ where age = 25;
db.users.update({name: 'Lisi'}, {$inc: {age: 50}}, false, true);
相当于:update users set age = age + 50 where name = ‘Lisi’;
db.users.update({name: 'Lisi'}, {$inc: {age: 50}, $set: {name: 'hoho'}}, false, true);
相当于:update users set age = age + 50, name = ‘hoho’ where name = ‘Lisi’;
删除
db.users.remove({age: 132});
查询修改删除
1
2
3
4
5
6
7
8
9
10
11
12
13db.users.findAndModify({
query: {age: {$gte: 25}},
sort: {age: -1},
update: {$set: {name: 'a2'}, $inc: {age: 2}},
remove: true
});
db.runCommand({ findandmodify : "users",
query: {age: {$gte: 25}},
sort: {age: -1},
update: {$set: {name: 'a2'}, $inc: {age: 2}},
remove: true
});
update 或 remove 其中一个是必须的参数; 其他参数可选。 |参数|详解|默认值| |—|—|—| |query|查询过滤条件|{}| |sort|如果多个文档符合查询过滤条件,将以该参数指定的排列方式选择出排在首位的对象,该对象将被操作|{}| |remove|若为true,被选中对象将在返回前被删除|N/A| |update|一个 修改器对象|N/A| |new|若为true,将返回修改后的对象而不是原始对象。在删除操作中,该参数被忽略。|false| |fields|参见Retrieving a Subset of Fields (1.5.0+)|All fields| |upsert|创建新对象若查询结果为空。 示例 (1.5.4+)|false|
语句块操作
简单Hello World
print("Hello World!");
这种写法调用了print函数,和直接写入”Hello World!”的效果是一样的;将一个对象转换成json
1
2tojson(new Object());
tojson(new Object('a'));循环添加数据
1
2
3> for (var i = 0; i < 30; i++) {
... db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});
... };
这样就循环添加了30条数据,同样也可以省略括号的写法
1 | > for (var i = 0; i < 30; i++) db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2}); |
也是可以的,当你用db.users.find()查询的时候,显示多条数据而无法一页显示的情况下,可以用it查看下一页的信息;
- find 游标查询
1
2
3
4>var cursor = db.users.find();
> while (cursor.hasNext()) {
printjson(cursor.next());
}
这样就查询所有的users信息,同样可以这样写
1 | var cursor = db.users.find(); |
同样可以省略{}号
forEach迭代循环
1
2db.users.find().forEach(printjson);
forEach中必须传递一个函数来处理每条迭代的数据信息将find游标当数组处理
1
2var cursor = db.users.find();
cursor[4];
取得下标索引为4的那条数据 既然可以当做数组处理,那么就可以获得它的长度:cursor.length();或者cursor.count(); 那样我们也可以用循环显示数据
1 | for (var i = 0, len = c.length(); i < len; i++) printjson(c[i]); |
- 将find游标转换成数组
1
2> var arr = db.users.find().toArray();
> printjson(arr[2]);
用toArray方法将其转换为数组
- 定制我们自己的查询结果
只显示age <= 28的并且只显示age这列数据
1
2db.users.find({age: {$lte: 28}}, {age: 1}).forEach(printjson);
db.users.find({age: {$lte: 28}}, {age: true}).forEach(printjson);
排除age的列
1 | db.users.find({age: {$lte: 28}}, {age: false}).forEach(printjson); |
- forEach传递函数显示信息
1
db.things.find({x:4}).forEach(function(x) {print(tojson(x));});
上面介绍过forEach需要传递一个函数,函数会接受一个参数,就是当前循环的对象,然后在函数体重处理传入的参数