MongoDB 入门

什么是 MongoDB ?
MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统。
在高负载的情况下,添加更多的节点,可以保证服务器性能。
MongoDB 旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。
MongoDB 将数据存储为一个文档,数据结构由键值 (key=>value) 对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。

安装

下载地址:https://www.mongodb.org/downloads

Windows中安装

在 Windows 系统上安装 MongoDB 数据库是件非常简单的事情,下载可执行安装文件(exe),双击安装即可。
MongoDB 服务器运行命令:MongoDB 安装目录/bin/mongod.exe
MongoDB 客户端运行命令:MongoDB 安装目录/bin/mongo.exe

Ubuntu 安装

参考 官方文档,我的环境 Ubuntu 14.04

1
2
3
4
5
6
7
8
9
10
11
# 下载密钥文件
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927

# 在 source.list 中增加 MongoDB 源的配置
$ echo "deb https://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list

# 更新 apt 源
$ sudo apt-get update

# 安装 MongoDB
$ sudo apt-get install -y mongodb-org=3.2.6 mongodb-org-server=3.2.6 mongodb-org-shell=3.2.6 mongodb-org-mongos=3.2.6 mongodb-org-tools=3.2.6

上述命令执行完则安装完成,安装成功后 mongod 服务会自动启动,下面检测一下是否安装成功。

1
2
$ sudo service mongod status
mongod start/running, process 3841

如果没有启动那么手动启动 mongod 服务

1
2
3
4
5
6
7
8
# 启动服务
$ sudo service mongod start

# 停止服务
$ sudo service mongod stop

# 重启服务
$ sudo service mongod restart

开启后,通过 /var/log/mongodb/mongod.log 查看日志文件。

配置

配置文件放在 /etc/mongod.conf
默认访问端口为 27017,数据库文件存放目录为 /var/lib/mongodb ,日志文件目录为 /var/log/mongodb/mongod.log

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
39
40
41
# mongod.conf

# for documentation of all options, see:
# https://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
# engine:
# mmapv1:
# wiredTiger:

# where to write logging data.
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log

# network interfaces
net:
port: 27017
bindIp: 127.0.0.1


#processManagement:

#security:

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:

基本使用

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
39
40
41
42
43
44
45
46
47
48
# MongoDB 的相关命令
$ mongo --help
MongoDB shell version: 3.2.6
usage: mongo [options] [db address] [file names (ending in .js)]
db address can be:
foo foo database on local machine
192.169.0.5/foo foo database on 192.168.0.5 machine
192.169.0.5:9999/foo foo database on 192.168.0.5 machine on port 9999
Options:
--shell run the shell after executing files
--nodb don't connect to mongod on startup - no
'db address' arg expected
--norc will not run the ".mongorc.js" file on
start up
--quiet be less chatty
--port arg port to connect to
--host arg server to connect to
--eval arg evaluate javascript
-h [ --help ] show this usage information
--version show version information
--verbose increase verbosity
--ipv6 enable IPv6 support (disabled by default)
--disableJavaScriptJIT disable the Javascript Just In Time
compiler
--enableJavaScriptProtection disable automatic JavaScript function
marshalling
--ssl use SSL for all connections
--sslCAFile arg Certificate Authority file for SSL
--sslPEMKeyFile arg PEM certificate/key file for SSL
--sslPEMKeyPassword arg password for key in PEM file for SSL
--sslCRLFile arg Certificate Revocation List file for SSL
--sslAllowInvalidHostnames allow connections to servers with
non-matching hostnames
--sslAllowInvalidCertificates allow connections to servers with invalid
certificates
--sslFIPSMode activate FIPS 140-2 mode at startup

Authentication Options:
-u [ --username ] arg username for authentication
-p [ --password ] arg password for authentication
--authenticationDatabase arg user source (defaults to dbname)
--authenticationMechanism arg authentication mechanism
--gssapiServiceName arg (=mongodb) Service name to use when authenticating
using GSSAPI/Kerberos
--gssapiHostName arg Remote host name to use for purpose of
GSSAPI/Kerberos authentication

file names: a list of files to run. files have to end in .js and will exit after unless --shell is specified

从上面的帮助可以看到 mongo 的使用,现在使用 mongo 命令访问 MongoDB 服务

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
$ mongo
MongoDB shell version: 3.2.6
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
https://docs.mongodb.org/
Questions? Try the support group
https://groups.google.com/group/mongodb-user

# 查看帮助
> help
db.help() help on db methods
db.mycoll.help() help on collection methods
sh.help() sharding helpers
rs.help() replica set helpers
help admin administrative help
help connect connecting to a db help
help keys key shortcuts
help misc misc things to know
help mr mapreduce

show dbs show database names
show collections show collections in current database
show users show users in current database
show profile show most recent system.profile entries with time >= 1ms
show logs show the accessible logger names
show log [name] prints out the last segment of log in memory, 'global' is default
use <db_name> set current database
db.foo.find() list objects in collection foo
db.foo.find( { a : 1 } ) list objects in foo where a == 1
it result of the last line evaluated; use to further iterate
DBQuery.shellBatchSize = x set default number of items to display on shell
exit quit the mongo shell
>

相关操作命令

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
39
40
41
42
43
44
45
46
47
48
49
50
51
# 连接数据库
$ mongo 127.0.0.1:27017

# 查看已有的数据库
> show dbs

# 切换/创建数据库
> use blogdb

# 显示当前数据库对象或集合
> db
blogdb

# 删除数据库
> db.dropDatabase()
{ "dropped" : "blogdb", "ok" : 1 }

# 向集合 user 中插入一条数据,如果集合不存在则创建
> db.user.insert({name:'hanks',age:22})
WriteResult({ "nInserted" : 1 })

# 查看当前数据库中是所以集合
> show collections
user
course

# 查询所以数据
> db.user.find()
{ "_id" : ObjectId("574021487ca7760c7927ea1b"), "name" : "hanks", "age" : 22 }
{ "_id" : ObjectId("5740214e7ca7760c7927ea1c"), "name" : "kiya", "age" : 22 }

# 条件查询
> db.user.find({name:'hanks'})
{ "_id" : ObjectId("574021487ca7760c7927ea1b"), "name" : "hanks", "age" : 22 }

# 删除
> db.user.remove({name:'hanks'})
WriteResult({ "nRemoved" : 1 })

# 覆盖更新
> db.user.update({name:'hanks'}, {age:'22'})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.user.find({name:'hanks'})
{ "_id" : ObjectId("5740239c7ca7760c7927ea20"), "age" : "22" }

# 更新某个字段
> db.user.update({name:'kiya'}, {$set:{age:'20'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.user.find({name:'kiya'},)
{ "_id" : ObjectId("574023a37ca7760c7927ea21"), "name" : "kiya", "age" : "20" }


相关链接

https://www.mongodb.com
https://www.runoob.com/mongodb/mongodb-tutorial.html

文章来自: https://hanks.pub