目录

2.1. Install 安装MongoDB
2.1.1. Quickstart
2.1.1.1. 二进制tar包安装2.1.1.2. Ubuntu MongoDB2.1.1.3. CentOS MongoDB2.1.1.4. 从官网安装最新版本的 MongoDB 3.4
2.1.1.4.1. Server2.1.1.4.2. Client2.1.1.4.3. 工具
2.1.1.5. MongoDB + Hadoop
2.1.2. Replication
2.1.2.1. Master2.1.2.2. Slave2.1.2.3. 测试
2.1.3. Drivers
2.1.3.1. Using MongoDB in PHP
2.2. MongoDB 管理
2.2.1. Security and Authentication
2.2.1.1. 超级管理员2.2.1.2. 数据库访问用户2.2.1.3. 数据库监控用户2.2.1.4. 删除用户2.2.1.5. 更新角色
2.2.2. Unique Indexes
2.2.2.1. 索引管理
2.2.2.1.1. 唯一索引
2.3. 命令工具
2.3.1. mongo - MongoDB Shell
2.3.1.1. eval2.3.1.2. help2.3.1.3. 登陆认证
2.3.2. mongodump - Backup
2.3.2.1. 远程备份2.3.2.2. 本地备份
2.3.3. mongorestore
2.3.3.1. 远程回复2.3.3.2. 本地恢复2.3.3.3. filter
2.3.4. mongostat2.3.5. mongotop2.3.6. mongofiles - Browse and modify a GridFS filesystem.
2.3.6.1. list 浏览文件2.3.6.2. put 上传文件2.3.6.3. get 下载2.3.6.4. delete 删除
2.4. MongoDB Shell
2.4.1. show 查看命令
2.4.1.1. show dbs2.4.1.2. show collections2.4.1.3. show users2.4.1.4. show profile
2.4.2. 切换数据库2.4.3. save2.4.4. insert2.4.5. update2.4.6. remove
2.4.6.1. 删除条件使用 _id
2.4.7. 删除 collection2.4.8. count()2.4.9. group()2.4.10. find() MongoDB 2.x2.4.11. find() MongoDB 3.x
2.4.11.1. Query2.4.11.2. 包含字段2.4.11.3. 排除字段2.4.11.4. sort()
2.4.12. 管道操作2.4.13. shutdownServer2.4.14. aggregate
2.4.14.1. project
2.4.14.1.1. $split2.4.14.1.2. substr
2.4.14.2. groupby + sum
2.5. Mongo Admin UI
2.5.1. RockMongo2.5.2. MongoVUE
2.6. Map-Reduce
2.6.1. 使用 Map-Reduce 统计Web 服务器 access.log 日志文件
2.7. FAQ
2.7.1. MongoDB 3.x 启用认证后恢复数据库需指定 collection2.7.2. MongoDB 2.x 早期版本用户管理

http://www.mongodb.org/

2.1. Install 安装MongoDB

2.1.1. Quickstart

2.1.1.1. 二进制tar包安装

Install MongoDB

wget http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-1.5.5.tgzdebian:/srv# tar zxf mongodb-linux-x86_64-1.5.5.tgz
debian:/srv# ln -s mongodb-linux-x86_64-1.5.5 mongodb

Create a data directory

By default MongoDB will store data in /data/db, but it won't automatically create that directory. To create it, do:

$ sudo mkdir -p /data/db/
$ sudo chown `id -u` /data/db

You can also tell MongoDB to use a different data directory, with the --dbpath option.

Run and connect to the server

First, start the MongoDB server in one terminal:

$ ./mongodb/bin/mongod

In a separate terminal, start the shell, which will connect to localhost by default:

$ ./mongodb/bin/mongo
> db.foo.save( { a : 1 } )
> db.foo.find()

Congratulations, you've just saved and retrieved your first document with MongoDB!

例 2.1. MongoDB Test

debian:/srv/mongodb/bin# ./mongo
MongoDB shell version: 1.5.5
connecting to: test
[initandlisten] Thu Jul 22 16:42:07 connection accepted from 127.0.0.1:42876 #1
> db.foo.save({a:1})
Thu Jul 22 16:42:23 allocating new datafile /data/db/test.ns, filling with zeroes...
Thu Jul 22 16:42:23 done allocating datafile /data/db/test.ns, size: 16MB,  took 0.025 secs
Thu Jul 22 16:42:23 allocating new datafile /data/db/test.0, filling with zeroes...
Thu Jul 22 16:42:23 done allocating datafile /data/db/test.0, size: 64MB,  took 0.105 secs
[conn1] Thu Jul 22 16:42:23 building new index on { _id: 1 } for test.foo
[conn1] Thu Jul 22 16:42:23 Buildindex test.foo idxNo:0 { name: "_id_", ns: "test.foo", key: { _id: 1 } }
[conn1] Thu Jul 22 16:42:23 done for 0 records 0secs
[conn1] Thu Jul 22 16:42:23 insert test.foo 136ms
> Thu Jul 22 16:42:23 allocating new datafile /data/db/test.1, filling with zeroes...
Thu Jul 22 16:42:24 done allocating datafile /data/db/test.1, size: 128MB,  took 0.228 secs
> db.foo.find()
{ "_id" : ObjectId("4c48046f74050cbf6c9a0ef6"), "a" : 1 }> use neo
switched to db neo
> db.foo.save({a:1})
Thu Jul 22 16:54:50 allocating new datafile /data/db/neo.ns, filling with zeroes...
Thu Jul 22 16:54:50 done allocating datafile /data/db/neo.ns, size: 16MB,  took 0.026 secs
Thu Jul 22 16:54:50 allocating new datafile /data/db/neo.0, filling with zeroes...
Thu Jul 22 16:54:50 done allocating datafile /data/db/neo.0, size: 64MB,  took 0.122 secs
[conn1] Thu Jul 22 16:54:50 building new index on { _id: 1 } for neo.foo
[conn1] Thu Jul 22 16:54:50 Buildindex neo.foo idxNo:0 { name: "_id_", ns: "neo.foo", key: { _id: 1 } }
Thu Jul 22 16:54:50 allocating new datafile /data/db/neo.1, filling with zeroes...
[conn1] Thu Jul 22 16:54:50 done for 0 records 0.01secs
[conn1] Thu Jul 22 16:54:50 insert neo.foo 164ms
> Thu Jul 22 16:54:50 done allocating datafile /data/db/neo.1, size: 128MB,  took 0.217 secs> db.foo.find()
{ "_id" : ObjectId("4c48075a74050cbf6c9a0ef7"), "a" : 1 }
>> db.neo.save({a:1})
[conn1] Thu Jul 22 16:58:32 building new index on { _id: 1 } for neo.neo
[conn1] Thu Jul 22 16:58:32 Buildindex neo.neo idxNo:0 { name: "_id_", ns: "neo.neo", key: { _id: 1 } }
[conn1] Thu Jul 22 16:58:32 done for 0 records 0.024secs
> db.neo.find()
{ "_id" : ObjectId("4c48083874050cbf6c9a0ef8"), "a" : 1 }

Starting Mongo

Running as a Daemon

 $ ./mongod --fork --logpath /var/log/mongodb.log --logappend

2.1.1.2. Ubuntu MongoDB

$ sudo apt-get install mongodb-server mongodb-clients
$ /etc/init.d/mongodb
Usage: /etc/init.d/mongodb {start|stop|force-stop|restart|force-reload|status}

2.1.1.3. CentOS MongoDB

CentOS 默认 MongoDB 是 2.6.12

[root@iZ623h9icu8Z ~]# yum info mongodb
Loaded plugins: langpacks
Repodata is over 2 weeks old. Install yum-cron? Or run: yum makecache fast
Available Packages
Name        : mongodb
Arch        : x86_64
Version     : 2.6.12
Release     : 3.el7
Size        : 43 M
Repo        : epel/x86_64
Summary     : High-performance, schema-free document-oriented database
URL         : http://www.mongodb.org
License     : AGPLv3 and zlib and ASL 2.0
Description : Mongo (from "humongous") is a high-performance, open source, schema-free: document-oriented database. MongoDB is written in C++ and offers the following: features::     * Collection oriented storage: easy storage of object/JSON-style data:     * Dynamic queries:     * Full index support, including on inner objects and embedded arrays:     * Query profiling:     * Replication and fail-over support:     * Efficient storage of binary data including large objects (e.g. photos:     and videos):     * Auto-sharding for cloud-level scalability (currently in early alpha):     * Commercial Support Available: : A key goal of MongoDB is to bridge the gap between key/value stores (which are: fast and highly scalable) and traditional RDBMS systems (which are deep in: functionality).
# yum install mongodb-server# chkconfig mongod on# service mongod start

单独安装客户端

# yum install mongodb

2.1.1.4. 从官网安装最新版本的 MongoDB 3.4

官网的rpm包是如下

[root@netkiller ~]# yum search mongodb | grep "\-org"
mongodb-org.x86_64 : MongoDB open source document-oriented database system
mongodb-org-mongos.x86_64 : MongoDB sharded cluster query router
mongodb-org-server.x86_64 : MongoDB database server
mongodb-org-shell.x86_64 : MongoDB shell client
mongodb-org-tools.x86_64 : MongoDB tools            
#!/bin/sh
cat << 'EOF' >> /etc/yum.repos.d/mongodb-org-3.4.repo
[mongodb-org-3.4]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.4.asc
EOF
2.1.1.4.1. Server

yum install -y mongodb-org-servercp /etc/mongod.conf{,.original}systemctl is-enabled mongod
systemctl start mongod

2.1.1.4.2. Client

yum install -y mongodb-org-shell              
[root@netkiller ~]# mongoMongoDB shell version v3.4.0
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.0
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, seehttp://docs.mongodb.org/
Questions? Try the support grouphttp://groups.google.com/group/mongodb-user
Server has startup warnings:
2016-11-30T11:34:36.493+0800 I STORAGE  [initandlisten]
2016-11-30T11:34:36.560+0800 I CONTROL  [initandlisten]
2016-11-30T11:34:36.560+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2016-11-30T11:34:36.560+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2016-11-30T11:34:36.560+0800 I CONTROL  [initandlisten]
2016-11-30T11:34:36.560+0800 I CONTROL  [initandlisten]
2016-11-30T11:34:36.560+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2016-11-30T11:34:36.560+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2016-11-30T11:34:36.560+0800 I CONTROL  [initandlisten]
2016-11-30T11:34:36.560+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2016-11-30T11:34:36.560+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2016-11-30T11:34:36.560+0800 I CONTROL  [initandlisten]
> show dbs
admin  0.000GB
local  0.000GB
> exit
bye

2.1.1.4.3. 工具

# yum install mongodb-org-tools# rpm -ql mongodb-org-tools.x86_64 0:3.4.1-1.el7
/usr/bin/bsondump
/usr/bin/mongodump
/usr/bin/mongoexport
/usr/bin/mongofiles
/usr/bin/mongoimport
/usr/bin/mongooplog
/usr/bin/mongoperf
/usr/bin/mongorestore
/usr/bin/mongostat
/usr/bin/mongotop
/usr/share/man/man1/bsondump.1
/usr/share/man/man1/mongodump.1
/usr/share/man/man1/mongoexport.1
/usr/share/man/man1/mongofiles.1
/usr/share/man/man1/mongoimport.1
/usr/share/man/man1/mongooplog.1
/usr/share/man/man1/mongoperf.1
/usr/share/man/man1/mongorestore.1
/usr/share/man/man1/mongostat.1
/usr/share/man/man1/mongotop.1

2.1.1.5. MongoDB + Hadoop

Hadoop Connector

http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-hadoop/

git clone https://github.com/mongodb/mongo-hadoop.git
git checkout release-1.0
# vim build.sbt
hadoopRelease in ThisBuild := "cdh4"
./sbt package
wget --no-check-certificate https://github.com/downloads/mongodb/mongo-java-driver/mongo-2.7.3.jar
cp mongo-2.7.3.jar /usr/lib/hadoop/lib/
cp core/target/mongo-hadoop-core_cdh3u3-1.0.0.jar /usr/lib/hadoop/lib/

待续......

2.1.2. Replication

很多教程上面采用手工配置主从复制,我不建议你这样启动,请采用修改/etc/mongod.conf配置文件的方案。

创建主:mongod –port 27017 –dbpath /var/lib/mongodb –master创建从:mongod –port 27017 –dbpath /var/lib/mongodb –slave –source master_ip_address:27017

2.1.2.1. Master

sed -i "s/#master = true/master = true/" /etc/mongod.confsystemctl restart  mongod

2.1.2.2. Slave

sed -i "s/#slave = true/slave = true/" /etc/mongod.conf
sed -i "s/#source = arg/source = mongodb.master.example.com/" /etc/mongod.confsystemctl restart  mongod

2.1.2.3. 测试

进入 Master

[root@localhost ~]# mongo
MongoDB shell version: 2.6.11
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, seehttp://docs.mongodb.org/
Questions? Try the support grouphttp://groups.google.com/group/mongodb-user
Server has startup warnings:
2015-11-14T15:51:21.215+0800 [initandlisten]
2015-11-14T15:51:21.215+0800 [initandlisten] ** WARNING: Readahead for /var/lib/mongodb is set to 4096KB
2015-11-14T15:51:21.215+0800 [initandlisten] **          We suggest setting it to 256KB (512 sectors) or less
2015-11-14T15:51:21.215+0800 [initandlisten] **          http://dochub.mongodb.org/core/readahead
>
>
> db.foo.save({'name':'neo','address':{'city':'shenzhen','post':518000},'phone':[13113668890,13322993040]})
WriteResult({ "nInserted" : 1 })
> db.foo.find();
{ "_id" : ObjectId("5646e881a11081d5998bf70c"), "name" : "neo", "address" : { "city" : "shenzhen", "post" : 518000 }, "phone" : [ 13113668890, 13322993040 ] }
>

进入 Slave

[root@localhost ~]# mongo
MongoDB shell version: 2.6.11
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, seehttp://docs.mongodb.org/
Questions? Try the support grouphttp://groups.google.com/group/mongodb-user
Server has startup warnings:
2015-11-14T15:51:23.668+0800 [initandlisten]
2015-11-14T15:51:23.668+0800 [initandlisten] ** WARNING: Readahead for /var/lib/mongodb is set to 4096KB
2015-11-14T15:51:23.668+0800 [initandlisten] **          We suggest setting it to 256KB (512 sectors) or less
2015-11-14T15:51:23.668+0800 [initandlisten] **          http://dochub.mongodb.org/core/readahead
> db.foo.find();
{ "_id" : ObjectId("5646e881a11081d5998bf70c"), "name" : "neo", "address" : { "city" : "shenzhen", "post" : 518000 }, "phone" : [ 13113668890, 13322993040 ] }
>

2.1.3. Drivers

2.1.3.1. Using MongoDB in PHP

Installing the PHP Driver

sudo pecl install mongo

Open your php.ini file and add to it:

extension=mongo.so

例 2.2. Using MongoDB in PHP

[root@subversion html]# cat mongo.php
<?php// connect
$m = new Mongo('192.168.3.9');// select a database
$db = $m->comedy;
$collection = $db->cartoons;// add an element
$obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
$collection->insert($obj);// add another element, with a different "shape"
$obj = array( "title" => "XKCD", "online" => true );
$collection->insert($obj);// find everything in the collection
$cursor = $collection->find();// iterate through the results
foreach ($cursor as $obj) {echo $obj["title"] . "\n";
}// disconnect
$m->close();?>
[root@subversion html]# php mongo.php
Calvin and Hobbes
XKCD
[root@subversion html]# php mongo.php
Calvin and Hobbes
XKCD
Calvin and Hobbes
XKCD
> use comedy
switched to db comedy
> db.foo.find()
> db.cartoons.find()
{ "_id" : ObjectId("4c481d2b9503c17611000000"), "title" : "Calvin and Hobbes", "author" : "Bill Watterson" }
{ "_id" : ObjectId("4c481d2b9503c17611010000"), "title" : "XKCD", "online" : true }
{ "_id" : ObjectId("4c481d2f9503c17711000000"), "title" : "Calvin and Hobbes", "author" : "Bill Watterson" }
{ "_id" : ObjectId("4c481d2f9503c17711010000"), "title" : "XKCD", "online" : true }
>

原文出处:Netkiller 系列 手札
本文作者:陈景峯
转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明。

第 2 章 MongoDB相关推荐

  1. 第一章 MongoDb概述

    版本修改历史 版本 修改内容 修改人 日期 1.0 创建文档 李乐 2010-6-30 第一章 MongoDb概述 集文档数据库,键值对存储和关系型数据库的优点于一身. MongoDB (名称来自&q ...

  2. 【大数据存储技术】第7章 MongoDB 的原理和使用

    文章目录 第7章 MongoDB 的原理和使用 7.1 概述 7.2 MongoDB 技术原理 7.2.1 文档和集合 7.2.2 分片机制和集群架构 7.2.3 CouchDB 简介 7.3 安装配 ...

  3. 第10章 MongoDB 删除数据库教程

    MongoDB 删除database 语法 MongoDB 删除database的语法格式如下: db.dropDatabase() 删除当前database,默认为 test,尊敬的读者您可以使用 ...

  4. 第46章 MongoDB 自动增长教程

    第46章 MongoDB 自动增长教程 MongoDB 没有像 SQL 一样有自动增长的功能, MongoDB 的 _id 是系统自动生成的12字节唯一标识. 但在某些情况下,咱们可能需要实现 Obj ...

  5. 第五章 MongoDb索引优化 5.6

    7.删除索引 a.删除某个表中的所有索引 To delete all indexes on the specified collection: 命令行:db.collection.dropIndexe ...

  6. 第三章 MongoDb Java应用 3.2

    下面来看看3.1的运行结果: 运行结果: { "_id" : { "$oid" : "4c2845d8735efe55298d0dc9"} ...

  7. 第三章 MongoDb Java应用 3.1

    1.Java 应用示例 要使用Java操作MongoDB的话,要到官方网站下载一个驱动包,点击网站上的Drivers里面,可以看到目前支持的语言,非常的多--把包导入后,可以尝试来操作了(记得一定要开 ...

  8. 第五章 MongoDb索引优化 5.5

    6.唯一索引中的重复值处理  删除上述5中的索引,插入两行一样的记录 coll.dropIndex("rsc"); 查看索引: index --------- { "na ...

  9. 第五章 MongoDb索引优化 5.4

    5.唯一索引 先看看之前创建的,rsc索引: index --------- { "name" : "rsc_1" , "ns" : &qu ...

最新文章

  1. 5款实用的硬盘、SSD固态硬盘、U盘、储存卡磁盘性能测试工具绿色版
  2. [Xcode 实际操作]八、网络与多线程-(19)使用RunLoop使PerformSelector方法延迟动作的执行...
  3. redis订阅执行一段时间自动停止_面试系列 redis 分布式锁amp;数据一致性
  4. 小熊的人生回忆(三)
  5. 21岁还可以学php开发吗,PHP已经21岁了!
  6. java nio 连接数_Java NIO 基础一 NIO概念
  7. ibatis sql_Map中出现异常:Cause: java.lang.RuntimeException: JavaBeansDataExchange could not instantiate..
  8. vue-cli 外部引入vue-router报错 Uncaught TypeError: Cannot redefine property: $router
  9. 【图像算法】七种常见阈值分割代码(Otsu、最大熵、迭代法、自适应阀值、手动、迭代法、基本全局阈值法)...
  10. iphone 推送服务--Apple Push Notification Service
  11. python基础之列表、元组和字典
  12. SSH学习之Struts2获取表单数据
  13. 专业的格式转换工具pdf2cad发布v11,支持当前所有的Windows和Mac操作系统
  14. 计算机怎么求标准偏差,如何计算Excel标准偏差?您必须知道这两个技巧
  15. Java 简易五子棋游戏的编写
  16. 计算机游戏者战略编写员教程
  17. SQL -- 游标(详细)
  18. LVGL 8.2 meter with multiple arcs
  19. 【Basler相机】帧率太低解决方案
  20. 精益供应链管理与算法(随笔)

热门文章

  1. php form 后台函数,Discuz!开发之后台表单生成函数介绍
  2. java fst 入门 例子,Java FST.save方法代码示例
  3. iis php http500,IIS7.5 PHP环境HTTP经常500错误处理方法
  4. python的魔法方法
  5. 下面哪个对象能代表当前的HTML文件,Java基础练习选择题(5)
  6. mysql xa 使用_MySQL如何实现 XA 规范
  7. 图解TCPIP-MAC地址(数据链路层)
  8. scala trait
  9. Hadoop HIVE 创建表
  10. Sphinx 初始化项目