1.安装MongoDB社区版

# . 导入MongoDB public GPG Key
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5 # . 添加软件源
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list # . 更新本地软件包
sudo apt-get update # . 安装MongoDB
sudo apt-get install -y mongodb-org 根据教程,本地Ubuntu .04系统安装的是mongodb3.,安装的时候提示如下,会安装下面相关几个软件包:
Get: https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6/multiverse amd64 mongodb-org-shell amd64 3.6.0 [8,477 kB]
Get: https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6/multiverse amd64 mongodb-org-server amd64 3.6.0 [14.9 MB]
Get: https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6/multiverse amd64 mongodb-org-mongos amd64 3.6.0 [8,468 kB]
Get: https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6/multiverse amd64 mongodb-org-tools amd64 3.6.0 [34.9 MB]
Get: https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6/multiverse amd64 mongodb-org amd64 3.6.0 [3,524 B]

(最新版本的安装参考:https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/#install-mongodb-community-edition)

2.MongoDB的运行

# . 启动MongoDB
sudo service mongod start
# . 验证MongoDB是否启动成功(在/var/log/mongodb/mongod.log文件中看到下面这一行就表示启动成功)
[initandlisten] waiting for connections on port
# . 停止MongoDB进程
sudo service mongod stop
# . 重启MongoDB
sudo service mongod restart
# . 查看MongoDB运行状态
sudo service mongod status

sudo vim /etc/mongod.conf 查看mongod的配置文件,可以看到它默认的数据存储路径、log文件路径、IP接口等并根据需要修改:

# mongod.conf

# for documentation of all options, see:
# http://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:
bindIp: 127.0.0.1 # how the process runs
processManagement:
timeZoneInfo: /usr/share/zoneinfo #security: #operationProfiling: #replication: #sharding: ## Enterprise-Only Options: #auditLog: #snmp:

mongod.conf

【备注】

在配置文件中修改数据存储路径后(例如修改为/home/xxname/mongodb_data),若mongodb服务启动失败,查看日志 /var/log/mongodb/mongod.log 如果是因为数据存储路径的权限问题

exception in initAndListen: IllegalOperation: Attempted to create a lock file on a read-only directory: /home/xxname/mongodb_data, terminating

解决方法:

查看mongodb默认数据存储目录的权限:

$ ll -h | grep /var/lib/mongodb/
drwxr-xr-x mongodb mongodb .0K 7月 : mongodb/

对应地,通过 sudo chown -R mongodb /home/xxname/mongodb_data/ 将新数据目录的拥有者修改为一致即可:

$ cd /home/xxname/
$ ll -h | grep mongodb_data/
drwxrwxr-x mongodb xxname .0K 6月 : mongodb_data/

3.MongoDB的使用

# 查看版本
$ mongod --version
db version v3.6.0
git version: a57d8e71e6998a2d0afde7edc11bd23e5661c915
OpenSSL version: OpenSSL 1.0.2g Mar
allocator: tcmalloc
modules: none
build environment:
distmod: ubuntu1604
distarch: x86_64
target_arch: x86_64
# 查看帮助信息
$ mongod --help
Options:

General options:
-h [ --help ] show this usage information
--version show version information
-f [ --config ] arg configuration file specifying
additional options
-v [ --verbose ] [=arg(=v)] be more verbose (include multiple times
for more verbosity e.g. -vvvvv)
--quiet quieter output
--port arg specify port number - by default
--bind_ip arg comma separated list of ip addresses to
listen on - localhost by default
--bind_ip_all bind to all ip addresses
--ipv6 enable IPv6 support (disabled by
default)
--listenBacklog arg (=) set socket listen backlog size
--maxConns arg max number of simultaneous connections
- by default
--logpath arg log file to send write to instead of
stdout - has to be a file, not
directory
--syslog log to system's syslog facility instead
of file or stdout
--syslogFacility arg syslog facility used for mongodb syslog
message
--logappend append to logpath instead of
over-writing
--logRotate arg set the log rotation behavior
(rename|reopen)
--timeStampFormat arg Desired format for timestamps in log
messages. One of ctime, iso8601-utc or
iso8601-local
--pidfilepath arg full path to pidfile (if not set, no
pidfile is created)
--timeZoneInfo arg full path to time zone info directory,
e.g. /usr/share/zoneinfo
--keyFile arg private key for cluster authentication
--noauth run without security
--setParameter arg Set a configurable parameter
--transitionToAuth For rolling access control upgrade.
Attempt to authenticate over outgoing
connections and proceed regardless of
success. Accept incoming connections
with or without authentication.
--clusterAuthMode arg Authentication mode used for cluster
authentication. Alternatives are
(keyFile|sendKeyFile|sendX509|x509)
--nounixsocket disable listening on unix sockets
--unixSocketPrefix arg alternative directory for UNIX domain
sockets (defaults to /tmp)
--filePermissions arg permissions to set on UNIX domain
socket file - by default
--fork fork server process
--networkMessageCompressors [=arg(=disabled)] (=snappy)
Comma-separated list of compressors to
use for network messages
--auth run with security
--clusterIpSourceWhitelist arg Network CIDR specification of permitted
origin for `__system` access.
--slowms arg (=) value of slow for profile and console
log
--slowOpSampleRate arg (=) fraction of slow ops to include in the
profile and console log
--profile arg =off =slow, =all
--cpu periodically show cpu and iowait
utilization
--sysinfo print some diagnostic system
information
--noIndexBuildRetry don't retry any index builds that were
interrupted by shutdown
--noscripting disable scripting engine
--notablescan do not allow table scans
--shutdown kill a running server (for init
scripts) Replication options:
--oplogSize arg size to use (in MB) for replication op
log. default is % of disk space (i.e.
large is good) Master/slave options (old; use replica sets instead):
--master master mode
--slave slave mode
--source arg when slave: specify master as
<server:port>
--only arg when slave: specify a single database
to replicate
--slavedelay arg specify delay (in seconds) to be used
when applying master ops to slave
--autoresync automatically resync if slave data is
stale Replica set options:
--replSet arg arg is <setname>[/<optionalseedhostlist
>]
--replIndexPrefetch arg specify index prefetching behavior (if
secondary) [none|_id_only|all]
--enableMajorityReadConcern [=arg(=)] (=)
enables majority readConcern Sharding options:
--configsvr declare this is a config db of a
cluster; default port ; default
dir /data/configdb
--shardsvr declare this is a shard db of a
cluster; default port SSL options:
--sslOnNormalPorts use ssl on configured ports
--sslMode arg set the SSL operation mode
(disabled|allowSSL|preferSSL|requireSSL
)
--sslPEMKeyFile arg PEM file for ssl
--sslPEMKeyPassword arg PEM file password
--sslClusterFile arg Key file for internal SSL
authentication
--sslClusterPassword arg Internal authentication key file
password
--sslCAFile arg Certificate Authority file for SSL
--sslCRLFile arg Certificate Revocation List file for
SSL
--sslDisabledProtocols arg Comma separated list of TLS protocols
to disable [TLS1_0,TLS1_1,TLS1_2]
--sslWeakCertificateValidation allow client to connect without
presenting a certificate
--sslAllowConnectionsWithoutCertificates
allow client to connect without
presenting a certificate
--sslAllowInvalidHostnames Allow server certificates to provide
non-matching hostnames
--sslAllowInvalidCertificates allow connections to servers with
invalid certificates
--sslFIPSMode activate FIPS - mode at startup Storage options:
--storageEngine arg what storage engine to use - defaults
to wiredTiger if no data files present
--dbpath arg directory for datafiles - defaults to
/data/db
--directoryperdb each database will be stored in a
separate directory
--noprealloc disable data file preallocation - will
often hurt performance
--nssize arg (=) .ns file size (in MB) for new databases
--quota limits each database to a certain
number of files ( default)
--quotaFiles arg number of files allowed per db, implies
--quota
--smallfiles use a smaller default file size
--syncdelay arg (=) seconds between disk syncs (=never,
but not recommended)
--upgrade upgrade db if needed
--repair run repair on all dbs
--repairpath arg root directory for repair files -
defaults to dbpath
--journal enable journaling
--nojournal disable journaling (journaling is on by
default for bit)
--journalOptions arg journal diagnostic options
--journalCommitInterval arg how often to group/batch commit (ms) WiredTiger options:
--wiredTigerCacheSizeGB arg maximum amount of memory to allocate
for cache; defaults to / of physical
RAM
--wiredTigerJournalCompressor arg (=snappy)
use a compressor for log records
[none|snappy|zlib]
--wiredTigerDirectoryForIndexes Put indexes and data in different
directories
--wiredTigerCollectionBlockCompressor arg (=snappy)
block compression algorithm for
collection data [none|snappy|zlib]
--wiredTigerIndexPrefixCompression arg (=)
use prefix compression on row-store
leaf pages

数据库操作:

$ mongo   # 进入shell
MongoDB shell version v3.6.0
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
> show dbs; # 查看数据库列表
admin .000GB
config .000GB
local .000GB
>
use xxx_db_name
db.xxx_table_name.find() # 默认返回10条
. Import Example Dataset
$ mongoimport --db test --collection restaurants --drop --file ~/software/mongodb/primer-dataset.json
--06T15::19.136+ connected to: localhost
--06T15::19.137+ dropping: test.restaurants
--06T15::20.559+ imported documents . MongoDB Shell (mongo)
$ mongo
> 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 : } ) list objects in foo where a ==
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
> show dbs;
admin .000GB
config .000GB
local .000GB
test .005GB . Insert Data with the mongo Shell
> use test
switched to db test
> db.restaurants.insert(
{
"address" : {
"street" : "2 Avenue",
"zipcode" : "",
"building" : "",
"coord" : [ -73.9557413, 40.7720266 ]
},
"borough" : "Manhattan",
"cuisine" : "Italian",
"grades" : [
{
"date" : ISODate("2014-10-01T00:00:00Z"),
"grade" : "A",
"score" :
},
{
"date" : ISODate("2014-01-16T00:00:00Z"),
"grade" : "B",
"score" :
}
],
"name" : "Vella",
"restaurant_id" : ""
}
)
WriteResult({ "nInserted" : })
> If the document passed to the insert() method does not contain the _id field, the mongo shell automatically adds the field to the document and sets the field’s value to a generated ObjectId. 更多信息
insert() and Documents:
https://docs.mongodb.com/manual/core/document/
https://docs.mongodb.com/manual/tutorial/insert-documents/ . Find or Query Data with the mongo Shell
4.1 Query for All Documents in a Collection
调用find()方法,不加参数
db.restaurants.find()
The result set contains all documents in the restaurants collection. 4.2 Specify Equality Conditions
The query condition for an equality match on a field has the following form:
{ <field1>: <value1>, <field2>: <value2>, ... }
If the <field> is a top-level field and not a field in an embedded document or an array, you can either enclose the field name in quotes or omit the quotes.
If the <field> is in an embedded document or an array, use dot notation to access the field. With dot notation, you must enclose the dotted name in quotes. 4.2. Query by a Top Level Field
db.restaurants.find( { "borough": "Manhattan" } ) 4.2. Query by a Field in an Embedded Document
db.restaurants.find( { "address.zipcode": "" } )
To specify a condition on a field within an embedded document, use the dot notation. Dot notation requires quotes around the whole dotted field name. 4.2. Query by a Field in an Array
db.restaurants.find( { "grades.grade": "B" } )
The grades array contains embedded documents as its elements. To specify a condition on a field in these documents, use the dot notation. Dot notation requires quotes around the whole dotted field name. 4.3 Specify Conditions with Operators
MongoDB provides operators to specify query conditions, such as comparison operators. Although there are some exceptions, such as the $or and $and conditional operators, query conditions using operators generally have the following form:
{ <field1>: { <operator1>: <value1> } }
For a complete list of the operators, see query operators. 4.3. Greater Than Operator ($gt)
Query for documents whose grades array contains an embedded document with a field score greater than .
db.restaurants.find( { "grades.score": { $gt: } } ) 4.3. Less Than Operator ($lt)
Query for documents whose grades array contains an embedded document with a field score less than .
db.restaurants.find( { "grades.score": { $lt: } } ) . Combine Conditions
You can combine multiple query conditions in logical conjunction (ANDs) and logical disjunctions (OR). 5.1 Logical AND
用逗号隔开;匹配满足所有条件的documents
You can specify a logical conjunction (AND) for a list of query conditions by separating the conditions with a comma in the conditions document.
db.restaurants.find( { "cuisine": "Italian", "address.zipcode": "" } )
The result set includes only the documents that matched all specified criteria. 5.2 Logical OR
用$or表示;匹配满足任意一个条件的documents
You can specify a logical disjunction (OR) for a list of query conditions by using the $or query operator.
db.restaurants.find(
{ $or: [ { "cuisine": "Italian" }, { "address.zipcode": "" } ] }
)
The result set includes only the documents that match either conditions. . Sort Query Results
升序1,降序-
To specify an order for the result set, append the sort() method to the query. Pass to sort() method a document which contains the field(s) to sort by and the corresponding sort type, e.g. for ascending and - for descending.
For example, the following operation returns all documents in the restaurants collection, sorted first by the borough field in ascending order, and then, within each borough, by the "address.zipcode" field in ascending order:
db.restaurants.find().sort( { "borough": , "address.zipcode": } )
The operation returns the results sorted in the specified order.

增删改查

其它的数据增删改查等数据库操作有待更新补充。

4. 数据恢复

之前服务器宕机,通过U盘启动的方法将数据库文件复制到移动硬盘,重装服务器之后,需要重新安装mongodb(参照上面的第1步)和进行数据恢复。

数据恢复步骤:修改mongodb配置文件,将数据存储路径改为指向之前备份好的数据的存放路径:

sudo vim /etc/mongod.conf ,将 dbPath: /var/lib/mongodb 改为 dbPath: /home/xxname/mongodb_data  ;然后重新启动mongodb服务 sudo service mongod start 即可。

其中遇到几个问题:

安装mongodb执行到 sudo apt-get install -y mongodb-org 时,报错 E: Unable to locate package mongodb-org ,改为:

sudo apt-get install -y mongodb

这种方式安装到的是比较旧的版本(v2.6.0)

但是进行数据恢复的时候报错:

--25T11::08.153+ [initandlisten] exception in initAndListen:  Cannot start server. Detected data files in /home/algsuper/mongodb created by storage engine 'wiredTiger'. The configured storage engine is 'mmapv1'., terminating

原因:根据mongodb的Release Notes,在v2.6及之前版本的默认存储引擎是MMAPv1,在v3.0开始支持WiredTiger,而在v3.2之后将默认存储引擎改为WiredTiger。所以,由v3.6的mongodb (对应WiredTiger存储引擎)创建的备份数据,导不进v2.6的mongodb。

解决方法:从官网中安装最新版v4.0.0, sudo apt-get install -y mongodb-org 可行。

但是安装好之后,启动服务报了另一个错误 MongoDB Failed to start mongod.service: Unit mongodb.service is masked  ,需要配置服务

sudo vim /etc/systemd/system/mongodb.service

添加以下内容并保存:

[Unit]
Description=High-performance, schema-free document-oriented database
After=network.target [Service]
User=mongodb
ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf [Install]
WantedBy=multi-user.target

然后执行以下三个命令即可启动服务:

sudo systemctl enable mongod.service
sudo systemctl daemon-reload
sudo service mongod start

在数据恢复中,如果修改配置文件中的dbpath导致服务重启失败,参考第2点的备注修改数据存储目录的权限即可。

进入mongo的shell环境,能够查看到之前的数据库,数据恢复完成~

参考:

mongodb 安装使用备记

官方的安装和测试教程(很详细):Install MongoDB Community Edition on Ubuntu

MongoDB Failed to start mongod.service: Unit mongodb.service is masked

MongoDB 安装、运行、使用、数据恢复的更多相关文章

  1. win7 64位下 mongodb安装及命令运行

    有网友老催我把框架加上mongodb的支持,于是偶尔抽空看了看相关的文章. 今天有缘,就把mongodb安装了一下,中间遇到了小小的问题,So,把整个过程记录一下: 1:先上官网:http://www ...

  2. 在WIN7下安装运行mongodb 1)、下载MongoDB

    1).下载MongoDB http://downloads.mongodb.org/win32/mongodb-win32-i386-2.4.5.zip 下载Windows 32-bit版本并解压缩, ...

  3. Ubuntu 12.04上安装 MongoDB并运行

    Ubuntu 12.04上安装 MongoDB并运行 作者:凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/ 在Terminal输入 sudo apt-key ...

  4. 在WIN7下安装运行mongodb

    1).下载MongoDB http://downloads.mongodb.org/win32/mongodb-win32-i386-2.4.5.zip 下载Windows 32-bit版本并解压缩, ...

  5. [转]在WIN7下安装运行mongodb

    本文转自:http://www.cnblogs.com/snake-hand/p/3172376.html 1).下载MongoDB http://downloads.mongodb.org/win3 ...

  6. MongoDB下载+安装+运行

    一. 官网下载安装 MongoDB 提供了 OSX 平台上 64 位的安装包,你可以在官网下载安装包. 下载地址:MongoDB官网-Community Server 选择适合自己平台的版本, 下载对 ...

  7. MongoDB配置服务--MongoDB安装成为windows服务

    MongoDB安装成为windows服务 1.打开命令提示符(最好以管理员的身份打开),然后输入: mongod --logpath "D:\MongoDB\data\log\logs.tx ...

  8. MongoDB学习:(一)MongoDB安装

    MongoDB学习:(一)MongoDB安装 MongoDB介绍:     直接百科了: MongoDB安装: 1:下载安装: MongoDB安装:https://www.mongodb.com/do ...

  9. MongoDB 安装(Window/Linux)

    MongoDB安装在Windows上 在 Windows上,首先要安装 MongoDB下载最新发布的MongoDB: http://www.mongodb.org/downloads 确保得到正确的版 ...

随机推荐

  1. bat批处理以当前时间创建文本文件

    :: 表示注释 :: @表示不显示当前命令,只在后台执行 :: @echo off 表示以后执行的命令都不显示 :: set d=%,% 表示设置变量d为当前年月日,默认表示为例如:// :: set ...

  2. 算法学习 - ST表 - 稀疏表 - 解决RMQ问题

    2017-08-26 21:44:45 writer:pprp RMQ问题就是区间最大最小值查询问题: 这个SparseTable算法构造一个表,F[i][j] 表示 区间[i, i + 2 ^ j ...

  3. SpringBoot项目结构介绍

    一项目结构介绍 springboot框架本身对项目结构并没有特别的要求,但是按照最佳的项目结构可以帮助我们减少可能遇到的错误问题.结构如下: (1)应用主类SpringbootApplication应 ...

  4. PE文件格式学习之PE头移位

    以前刚开始学网络安全,是从免杀开始的.记得那时候杀毒软件还很弱.金山江民瑞星还存在. 那会什么原理也不懂,就一直瞎鼓捣.(后来转入渗透行列了) 这段时间一直在学PE格式,突然想起来以前很古老的PE文件 ...

  5. 使用httpclient提交表单数据加号(+)会被自动替换成空格的坑

    坑的场景: 今天使用httpclient-4.5.3版本,发送如下报文: { "idNo": "7+6+0+2ce722a546b39463bd62817fe57f8&q ...

  6. webstorm的安装、激活码、更换主题颜色的修改、汉化

    一.安装 1.解压webstorm11zh.rar,双击.exe文件,下一步安装,在安装结束前会提示输入激活码,这个从网上随便找一个可用的即可. 二.更换主题颜色: 1.先从网上找一个喜欢的主题颜色, ...

  7. 【Python】模块学习之Timer定时任务,递归定时自调获取博客浏览量

    Timer定时任务 下面是Timer函数的官方doc介绍信息 """ Call a function after a specified number of second ...

  8. 使用bootstrap时碰到问题$(...).modal is not a function

    我出现这个问题是,因为bootstrap没有正确引入. 除了bootstrap的路径需要被正确引入外,它引入时还要放在jquery.js后面,否则也会报这个错误.

  9. virtual dom & mvvm

    虚拟dom 用js对象来表示dom树的结构,然后用这个对象来构建一个真正的dom树插入文档中: 当状态有变时,重新构造一个新的对象树,然后比较新的和旧的树,记录两个数的差异: 把差异部分应用到真正的d ...

  10. angular之自定义 directive

    1,指令的创建至少需要一个带有@Directive装饰器修饰的控制器类.@Directive装饰器指定了一个选择器名称,用于指出与此指令相关联的属性的名字. 2,创建一个highlight.direc ...