MongoDB是面向文档的数据库。和关系型数据库不同的是它能非常方便的扩展字段。而且对于文件类型的内容有非常好的可塑性。如制作游戏的时候,我们对于一个role的数据结构的定义,可能不是从一开始就能固化好。策划可能对运营上线的游戏玩法的修改、增删可能会引起对于存储的字段有影响。如果使用的技术是传统的MySQL中的表中的字段来存储role的数据,将会需要开发者编写数据库变更的SQL语句,并且通知运维人员同步到全部服务器。这个过程可能需要还需要去编写检查脚本以防止在生产环境中可能未能将更新在全部服务器中执行完,而造成部分服务器的数据回档。如果使用MongoDB中的文档数据结构,就会比较方便了。MongoDB中的文档基本上是一个类似json语法的描述,存储到文件中的时候是使用的bson格式。
增删改查
mongo shell简单的用法
在mongo命令行也类似于mysql的命令行。他是使用js编写的。所以在这个命令行中能直接解析执行javascript的语法。
$ mongo
MongoDB shell version: 2.6.11
connecting to: test
> show dbs -- 查看本地全部数据库
admin (empty)
local 0.078GB
> db -- 查看在使用的数据库
test
> use local -- 切换数据库
switched to db local
> show collections -- 查看这个db里面的全部表
增
在test里面我们添加一条blog信息
> use local
switched to db local
> use test
switched to db test
> post = {"title":"LOL",
... "content":"league of legends is one of my favorite games.",
... "date":new Date()}
{
"title" : "LOL",
"content" : "league of legends is one of my favorite games.",
"date" : ISODate("2016-05-20T23:28:38.391Z")
}
> db.blog.insert(post)
WriteResult({ "nInserted" : 1 })
查
> db.blog.findOne()
{
"_id" : ObjectId("573f9e01e00e5fff255950f2"),
"title" : "LOL",
"content" : "league of legends is one of my favorite games.",
"date" : ISODate("2016-05-20T23:28:38.391Z")
}
改
> post.comments = []
[ ]
> db.blog.update({title:"LOL"},post)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.blog.findOne()
{
"_id" : ObjectId("573f9e01e00e5fff255950f2"),
"title" : "LOL",
"content" : "league of legends is one of my favorite games.",
"date" : ISODate("2016-05-20T23:28:38.391Z"),
"comments" : [ ]
}
删
> db.blog.remove({title:"LOL"},post)
WriteResult({ "nRemoved" : 1 })
> db.blog.findOne()
null
数据结构介绍
类型 | 说明 |
---|---|
null | null用于表示空值或者不存在的字段。 {“x”:null} |
布尔 | 布尔类型有两个值’true’和’false1’. {“X”:true} |
数值 | 64位浮点数。或者是{“x”:NumberInt(“3”)}{“x”:NumberLong(“3”)} |
字符串 | UTF-8字符串都可表示为字符串类型的数据: {“x” : “foobar”} |
日期 | 日期类型存储的是从标准纪元开始的毫秒数。不存储时区: {“X” : new Date()} |
正则表达式 | 文档中可以包含正则表达式,采用JavaScript的正则表达式语法: {“x” : /foobar/i} |
代码 | 文档中还可以包含JavaScript代码:{“x” : function() { /* …… */ }} |
导出/导入MongoDB
mongodump --help
Export MongoDB data to BSON files.
Options:
--help produce help message
-v [ --verbose ] be more verbose (include multiple times
for more verbosity e.g. -vvvvv)
--quiet silence all non error diagnostic
messages
--version print the program's version and exit
-h [ --host ] arg mongo host to connect to ( <set
name>/s1,s2 for sets)
--port arg server port. Can also use --host
hostname:port
--ipv6 enable IPv6 support (disabled by
default)
--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
-u [ --username ] arg username
-p [ --password ] arg password
--authenticationDatabase arg user source (defaults to dbname)
--authenticationMechanism arg (=MONGODB-CR)
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
--dbpath arg directly access mongod database files
in the given path, instead of
connecting to a mongod server - needs
to lock the data directory, so cannot
be used if a mongod is currently
accessing the same path
--directoryperdb each db is in a separate directory
(relevant only if dbpath specified)
--journal enable journaling (relevant only if
dbpath specified)
-d [ --db ] arg database to use
-c [ --collection ] arg collection to use (some commands)
-o [ --out ] arg (=dump) output directory or "-" for stdout
-q [ --query ] arg json query
--oplog Use oplog for point-in-time
snapshotting
--repair try to recover a crashed database
--forceTableScan force a table scan (do not use
$snapshot)
--dumpDbUsersAndRoles Dump user and role definitions for the
given database
mongodump -d test -o ./test.bson
$ mongodump -d test -o ./test
connected to: 127.0.0.1
2016-05-21T09:31:34.643+0800 DATABASE: test to ./test/test
2016-05-21T09:31:34.644+0800 test.system.indexes to ./test/test/system.indexes.bson
2016-05-21T09:31:34.644+0800 1 documents
2016-05-21T09:31:34.644+0800 test.blog to ./test/test/blog.bson
2016-05-21T09:31:34.645+0800 1 documents
2016-05-21T09:31:34.645+0800 Metadata for test.blog to ./test/test/blog.metadata.json
$ tree ./test
./test
└── test
├── blog.bson
├── blog.metadata.json
└── system.indexes.bson
1 directory, 3 files
$ mongorestore --help
Import BSON files into MongoDB.
usage: mongorestore [options] [directory or filename to restore from]
Options:
--help produce help message
-v [ --verbose ] be more verbose (include multiple times
for more verbosity e.g. -vvvvv)
--quiet silence all non error diagnostic
messages
--version print the program's version and exit
-h [ --host ] arg mongo host to connect to ( <set
name>/s1,s2 for sets)
--port arg server port. Can also use --host
hostname:port
--ipv6 enable IPv6 support (disabled by
default)
--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
-u [ --username ] arg username
-p [ --password ] arg password
--authenticationDatabase arg user source (defaults to dbname)
--authenticationMechanism arg (=MONGODB-CR)
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
--dbpath arg directly access mongod database files
in the given path, instead of
connecting to a mongod server - needs
to lock the data directory, so cannot
be used if a mongod is currently
accessing the same path
--directoryperdb each db is in a separate directory
(relevant only if dbpath specified)
--journal enable journaling (relevant only if
dbpath specified)
-d [ --db ] arg database to use
-c [ --collection ] arg collection to use (some commands)
--objcheck validate object before inserting
(default)
--noobjcheck don't validate object before inserting
--filter arg filter to apply before inserting
--drop drop each collection before import
--oplogReplay replay oplog for point-in-time restore
--oplogLimit arg include oplog entries before the
provided Timestamp (seconds[:ordinal])
during the oplog replay; the ordinal
value is optional
--keepIndexVersion don't upgrade indexes to newest version
--noOptionsRestore don't restore collection options
--noIndexRestore don't restore indexes
--restoreDbUsersAndRoles Restore user and role definitions for
the given database
--w arg (=0) minimum number of replicas per write
$ mongorestore -db test_duplicate ./test/test/
connected to: 127.0.0.1
2016-05-21T09:33:02.967+0800 ./test/test/blog.bson
2016-05-21T09:33:02.967+0800 going into namespace [test_duplicate.blog]
Restoring to test_duplicate.blog without dropping. Restored data will be inserted without raising errors; check your server log
1 objects found
2016-05-21T09:33:02.967+0800 Creating index: { key: { _id: 1 }, name: "_id_", ns: "test_duplicate.blog" }
$ mongo
MongoDB shell version: 2.6.11
connecting to: test
> use test_duplicate
switched to db test_duplicate
> db.blog.find()
{ "_id" : ObjectId("573fba64a1fc07b6731428f8"), "title" : "LOL", "content" : "league of legends is one of my favorite games.", "date" : ISODate("2016-05-21T01:30:55.673Z") }