db-mongo

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
2
cd ~
tar -xzvf mongodb-linux-x86_64-3.4.9.tgz -C /opt/modules/

进入modules文件夹

1
cd /opt/modules/

重命名为mongodb

1
2
mv mongodb-linux-x86_64-3.4.9 mongodb 
cd mongodb/
3.创建数据库存放目录和日志存放目录

将服务的数据存放在/opt/data目录下,需要创建db目录用于存放数据库文件,logs目录存放日志文件:

1
2
3
4
mkdir -p /opt/data/mongodb/data 
mkdir -p /opt/data/mongodb/data/db
mkdir -p /opt/data/mongodb/data/logs
touch /opt/data/mongodb/data/logs/mogodb.log
4.创建MongoDB配置文件mongodb.conf

mongodb.conf主要配置MongoDB的监听端口,数据库目录,日志存放位置,日志输出方式以及是否开启后台运行等:

1
2
cd /opt/data/mongodb/data/ 
vim mongodb.conf

mongodb.conf 具体配置信息如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
# 端口号 
port=27017
# 数据库路径
dbpath=/opt/data/mongodb/data/db
# 日志输出文件路径
logpath=/opt/data/mongodb/data/logs/mongodb.log
pidfilepath=/opt/data/mongodb/data/mongo.pid
# 设置后台运行
fork=true
# 日志输出方式
logappend=true
# 启动http界面,端口号为28017
httpinterface=true
5.启动MongoDB服务

执行以下命令启动MongoDB服务:

1
2
cd /opt/modules/mongodb/ 
bin/mongod --config /opt/data/mongodb/data/mongodb.conf

会打印下面信息: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环境

ubunut下安装

步骤
  1. Update Homebrew’s package database. In a system shell ,issue the following command:

    brew update

  2. 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

  3. 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

Replace with the path to the extracted MongoDB archive.

brew 安装结果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
brew install mongodb
==> Installing dependencies for mongodb: openssl
==> Installing mongodb dependency: openssl
==> Downloading https://homebrew.bintray.com/bottles/openssl-1.0.2h_1.el_capitan
######################################################################## 100.0%
==> Pouring openssl-1.0.2h_1.el_capitan.bottle.tar.gz
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
/usr/local/etc/openssl/certs

and run
/usr/local/opt/openssl/bin/c_rehash

This formula is keg-only, which means it was not symlinked into /usr/local.

Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries

Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:

LDFLAGS: -L/usr/local/opt/openssl/lib
CPPFLAGS: -I/usr/local/opt/openssl/include

==> Summary
🍺 /usr/local/Cellar/openssl/1.0.2h_1: 1,691 files, 12M
==> Installing mongodb
==> Downloading https://homebrew.bintray.com/bottles/mongodb-3.2.6.el_capitan.bo
######################################################################## 100.0%
==> Pouring mongodb-3.2.6.el_capitan.bottle.tar.gz
==> Caveats
To have launchd start mongodb now and restart at login:
brew services start mongodb
Or, if you don't want/need a background service you can just run:
mongod --config /usr/local/etc/mongod.conf
==> Summary
🍺 /usr/local/Cellar/mongodb/3.2.6: 17 files, 263.8M
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
    3
    mongo
    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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2016-03-05T19:23:55.763+0100 I CONTROL  [initandlisten] MongoDB starting : pid=52426 port=27017 dbpath=/data/db 64-bit host=Matthias-MBP
2016-03-05T19:23:55.764+0100 I CONTROL [initandlisten] db version v3.2.3
2016-03-05T19:23:55.764+0100 I CONTROL [initandlisten] git version: b326ba837cf6f49d65c2f85e1b70f6f31ece7937
2016-03-05T19:23:55.764+0100 I CONTROL [initandlisten] allocator: system
2016-03-05T19:23:55.764+0100 I CONTROL [initandlisten] modules: none
2016-03-05T19:23:55.764+0100 I CONTROL [initandlisten] build environment:
2016-03-05T19:23:55.764+0100 I CONTROL [initandlisten] distarch: x86_64
2016-03-05T19:23:55.764+0100 I CONTROL [initandlisten] target_arch: x86_64
2016-03-05T19:23:55.764+0100 I CONTROL [initandlisten] options: {}
2016-03-05T19:23:55.765+0100 I - [initandlisten] Detected data files in /data/db created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'.
2016-03-05T19:23:55.765+0100 I STORAGE [initandlisten] wiredtiger_open config: create,cache_size=4G,session_max=20000,eviction=(threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0),
2016-03-05T19:23:56.483+0100 I CONTROL [initandlisten]
2016-03-05T19:23:56.483+0100 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
2016-03-05T19:23:56.486+0100 I NETWORK [HostnameCanonicalizationWorker] Starting hostname canonicalization worker
2016-03-05T19:23:56.486+0100 I FTDC [initandlisten] Initializing full-time diagnostic data capture with directory '/data/db/diagnostic.data'
2016-03-05T19:23:56.488+0100 I NETWORK [initandlisten] waiting for connections on port 27017
2016-03-05T19:23:56.513+0100 W NETWORK [HostnameCanonicalizationWorker] Failed to obtain address information for hostname Matthias-MBP: nodename nor servname provided, or not known

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.

操作相关

数据库

  1. Help查看命令提示

    1
    2
    3
    4
    5
    help
    db.help();
    db.yourColl.help();
    db.youColl.find().help();
    rs.help();
  2. 切换/创建数据库

    1
    2
    >use yourDB;
    当创建一个集合(table)的时候会自动创建当前数据库
  3. 查询所有数据库

    1
    show dbs;
  4. 删除当前使用数据库

    1
    db.dropDatabase();
  5. 从指定主机上克隆数据库

    1
    2
    db.cloneDatabase(“127.0.0.1”);
    将指定机器上的数据库的数据克隆到当前数据库
  6. 从指定的机器上复制指定数据库数据到某个数据库

    1
    2
    db.copyDatabase("mydb", "temp", "127.0.0.1");
    将本机的mydb的数据复制到temp数据库中
  7. 修复当前数据库

    1
    db.repairDatabase();
  8. 查看当前使用的数据库

    1
    2
    3
    db.getName();
    db;
    db和getName方法是一样的效果,都可以查询当前使用的数据库
  9. 显示当前db状态

    1
    db.stats();
  10. 当前db版本

    1
    db.version();
  11. 查看当前db的链接机器地址

    1
    db.getMongo();

Collection聚集集合

  1. 创建一个聚集集合(table)

    1
    db.createCollection(“collName”, {size: 20, capped: 5, max: 100});
  2. 得到指定名称的聚集集合(table)

    1
    db.getCollection("account");
  3. 得到当前db的所有聚集集合

    1
    db.getCollectionNames();
  4. 显示当前db所有聚集索引的状态

    1
    db.printCollectionStats();

用户相关

  1. 添加一个用户
    1
    2
    db.addUser("name");
    db.addUser("userName", "pwd123", true);

添加用户、设置密码、是否只读

  1. 数据库认证、安全模式

    1
    db.auth("userName", "123123");
  2. 显示当前所有用户

    1
    show users;
  3. 删除用户

    1
    db.removeUser("userName");

其他

  1. 查询之前的错误信息

    1
    db.getPrevError();
  2. 清除错误记录

    1
    db.resetError();

Collection聚合集合操作

###查看聚集集合基本信息

  1. 查看帮助

    1
    db.yourColl.help();
  2. 查询当前集合的数据条数

    1
    db.yourColl.count();
  3. 查看数据空间大小

    1
    db.userInfo.dataSize();
  4. 得到当前聚集集合所在的db

    1
    db.userInfo.getDB();
  5. 得到当前聚集的状态

    1
    db.userInfo.stats();
  6. 得到聚集集合总大小

    1
    db.userInfo.totalSize();
  7. 聚集集合储存空间大小

    1
    db.userInfo.storageSize();
  8. Shard版本信息

    1
    db.userInfo.getShardVersion()
  9. 聚集集合重命名

    1
    db.userInfo.renameCollection("users");

将userInfo重命名为users

  1. 删除当前聚集集合
    1
    db.userInfo.drop();

聚集集合查询

  1. 查询所有记录
    1
    db.userInfo.find();

相当于:select * from userInfo; 默认每页显示20条记录,当显示不下的情况下,可以用it迭代命令查询下一页数据。注意:键入it命令不能带“;” 但是你可以设置每页显示数据的大小,用DBQuery.shellBatchSize = 50;这样每页就显示50条记录了。

  1. 查询去掉后的当前聚集集合中的某列的重复数据
    1
    db.userInfo.distinct("name");

会过滤掉name中的相同数据 相当于:select distict name from userInfo;

  1. 查询age = 22的记录 db.userInfo.find({"age": 22}); 相当于: select * from userInfo where age = 22;

  2. 查询age > 22的记录 db.userInfo.find({age: {$gt: 22}}); 相当于:select * from userInfo where age > 22;

  3. 查询age < 22的记录 db.userInfo.find({age: {$lt: 22}}); 相当于:select * from userInfo where age < 22;

  4. 查询age >= 25的记录 db.userInfo.find({age: {$gte: 25}}); 相当于:select * from userInfo where age >= 25;

  5. 查询age <= 25的记录 db.userInfo.find({age: {$lte: 25}});

  6. 查询age >= 23 并且 age <= 26 db.userInfo.find({age: {$gte: 23, $lte: 26}});

  7. 查询name中包含 mongo的数据 db.userInfo.find({name: /mongo/}); //相当于%% select * from userInfo where name like ‘%mongo%’;

  8. 查询name中以mongo开头的 db.userInfo.find({name: /^mongo/}); select * from userInfo where name like ‘mongo%’;

  9. 查询指定列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;

  1. 按照年龄排序 升序:db.userInfo.find().sort({age: 1}); 降序:db.userInfo.find().sort({age: -1});

  2. 查询name = zhangsan, age = 22的数据 db.userInfo.find({name: 'zhangsan', age: 22}); 相当于:select * from userInfo where name = ‘zhangsan’ and age = ‘22’;

  3. 查询前5条数据 db.userInfo.find().limit(5); 相当于:select top 5 * from userInfo;

  4. 查询10条以后的数据 db.userInfo.find().skip(10); 相当于:select * from userInfo where id not in ( select top 10 * from userInfo );

  5. 查询在5-10之间的数据 db.userInfo.find().limit(10).skip(5); 可用于分页,limit是pageSize,skip是第几页*pageSize

  6. or与 查询 db.userInfo.find({$or: [{age: 22}, {age: 25}]}); 相当于:select * from userInfo where age = 22 or age = 25;

  7. 查询第一条数据 db.userInfo.findOne(); 相当于:select top 1 * from userInfo; db.userInfo.find().limit(1);

  8. 查询某个结果集的记录条数 db.userInfo.find({age: {$gte: 25}}).count(); 相当于:select count(*) from userInfo where age >= 20;

  9. 按照某列进行排序 db.userInfo.find({sex: {$exists: true}}).count(); 相当于:select count(sex) from userInfo;

索引

  1. 创建索引

    1
    2
    db.userInfo.ensureIndex({name: 1});
    db.userInfo.ensureIndex({name: 1, ts: -1});
  2. 查询当前聚集集合所有索引 db.userInfo.getIndexes();

  3. 查看总索引记录大小 db.userInfo.totalIndexSize();

  4. 读取当前集合的所有index信息 db.users.reIndex();

  5. 删除指定索引 db.users.dropIndex("name_1");

  6. 删除所有索引索引 db.users.dropIndexes();

修改、添加、删除集合数据

  1. 添加 db.users.save({name: ‘zhangsan’, age: 25, sex: true}); 添加的数据的数据列,没有固定,根据添加的数据为准

  2. 修改 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’;

  1. 删除 db.users.remove({age: 132});

  2. 查询修改删除

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    db.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|

语句块操作

  1. 简单Hello World print("Hello World!"); 这种写法调用了print函数,和直接写入”Hello World!”的效果是一样的;

  2. 将一个对象转换成json

    1
    2
    tojson(new Object());
    tojson(new Object('a'));
  3. 循环添加数据

    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查看下一页的信息;

  1. find 游标查询
    1
    2
    3
    4
    >var cursor = db.users.find();
    > while (cursor.hasNext()) {
    printjson(cursor.next());
    }

这样就查询所有的users信息,同样可以这样写

1
2
var cursor = db.users.find();
while (cursor.hasNext()) { printjson(cursor.next); }

同样可以省略{}号

  1. forEach迭代循环

    1
    2
    db.users.find().forEach(printjson);
    forEach中必须传递一个函数来处理每条迭代的数据信息
  2. 将find游标当数组处理

    1
    2
    var 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]);
  1. 将find游标转换成数组
    1
    2
    > var arr = db.users.find().toArray();
    > printjson(arr[2]);

用toArray方法将其转换为数组

  1. 定制我们自己的查询结果 只显示age <= 28的并且只显示age这列数据
    1
    2
    db.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);
  1. forEach传递函数显示信息
    1
    db.things.find({x:4}).forEach(function(x) {print(tojson(x));});

上面介绍过forEach需要传递一个函数,函数会接受一个参数,就是当前循环的对象,然后在函数体重处理传入的参数

坚持原创技术分享,您的支持将鼓励我继续创作!