MongoDB 学习笔记(一)

1.安装 ,安装好弄,到官网下载下来 解压开来 就欧啦。下载地址在这里:下载地址

还有一些入门的概念


A document is the basic unit of data for MongoDB and is roughly equivalent to a
row in a relational database management system (but much more expressive).

文档是mongoDB的基本数据单元,和关系型数据库的一行数据一样,但是更灵活我感觉。


比如一个document可以存储{ "_id" : { "$oid" : "53abe1ab18713765b33f2738"} , "usrname" : "mongo" , "friends" : 32.0 , "enemies" : 2.0}


• Similarly, a collection can be thought of as a table with a dynamic schema.

 同样的一个colletion是啥呢 就是一个和关系型数据库的表类似,但是是动态模式(有道翻译我不是打广告)就是没有约束呗想怎么存就怎么存。


• A single instance of MongoDB can host multiple independent databases, each of

which can have its own collections.


一个示例可以支撑多个数据库,每个数据库又有自己的colletion,


• Every document has a special key, "_id", that is unique within a collection.

每隔文档都已自己的一个特殊的“_id”,在一个集合里边是唯一的。


• MongoDB comes with a simple but powerful JavaScript shell, which is useful for

the administration of MongoDB instances and data manipulation.

MongoDB有一个javascript外壳,由管理员用来管理数据库实例,和数据操作。(翻译完毕,英文来自mongodb_the_definitive_guide_2nd_edition.pdf  这里有下载 打个小广告http://download.csdn.net/detail/u014133453/7557425)



The keys in a document are strings. Any UTF-8 character is allowed in a key, with a few
notable exceptions:

只要是UTF-8就行 ,但是要注意


• Keys must not contain the character \0 (the null character). This character is used
to signify the end of a key.

键不能有\0  这个字符标志着键的结束


• The . and $ characters have some special properties and should be used only in
certain circumstances In general, they should be
considered reserved, and drivers will complain if they are used inappropriately.


这个   .     和 $  也不行,他俩有一些特殊的属性,只能用在特定的情况下,一般情况下认为这两哥们是被保留的司机就会抱怨如果用的不得当,显然不是这么翻译啊  如果用的不合适,驱动不一定会正常工作奥。


另外 mongodb 类型和大小写敏感

{"foo" : 3}
{"foo" : "3"}     not same

{"foo" : 3}
{"Foo" : 3}  not same too


另外啊  这个一个document 里边啊 不能有相同的key (书本写的就是严谨)

这就不行

{"greeting" : "Hello, world!", "greeting" : "Hello, MongoDB!"}


又另外 在document里 啊  键/值 是有顺序地  {"x" : 1, "y" : 2}   {"y" : 2, "x" : 1} 是不一样地


这个顺序不是很重要,所以你在设计你的模式的时候不能靠特定的格式 即使是这样mongoDB  也会将它重组。


虽然说collection 在上述原则上可以放置任意document但是我们为什么需要多余一个的collection呢 书上的原话啊 我翻译下



• Keeping different kinds of documents in the same collection can be a nightmare
for developers and admins. Developers need to make sure that each query is only
returning documents of a certain type or that the application code performing a
query can handle documents of different shapes. If we’re querying for blog posts,
it’s a hassle to weed out documents containing author data.


如果你把不同类型的document放在同一个collection下这对管理员和开发者都是噩梦。开发人员要确保每次查询返回特定的类型或者说程序代码能够处理的了不同类型的document。比我们查询帖子,我们剔除了包含作者信息的document是困难的好蹩脚。



• It is much faster to get a list of collections than to extract a list of the types in a
collection. For example, if we had a "type" field in each document that specified
whether the document was a “skim,” “whole,” or “chunky monkey,” it would be much
slower to find those three values in a single collection than to have three separate
collections and query the correct collection.


• Grouping documents of the same kind together in the same collection allows for
data locality. Getting several blog posts from a collection containing only posts will
likely require fewer disk seeks than getting the same posts from a collection con‐
taining posts and author data.



• We begin to impose some structure on our documents when we create indexes.
(This is especially true in the case of unique indexes.) These indexes are defined per
collection. By putting only documents of a single type into the same collection, we
can index our collections more efficiently.


又来了一些限制 ,collection的名字不能是空字符串,不能是\0  , 不能已system开头,为的是mongodb内部的collection

特别注意不能包含$字符

另外 子集合的概念




Subcollections are a great way to organize data in MongoDB, and their use is highly
recommended.


数据库的名字里不能包含这个

不能为空   /, \, ., ", *, <, >, :, |, ?, $, (a
single space), or \0 (the null character) 基本来书字母数字就行啦  小写 最长64字节  为什么呢包不准他数据库名会成为你文件名这就是为什么他又这么多限制



2.运行 在/bin 目录下有个mongod命令  先看看有什吗参数再说


  -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 - 27017 by default
  --bind_ip arg               comma separated list of ip addresses to listen on
                              - all local ips by default
  --maxConns arg              max number of simultaneous connections - 1000000 
                              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 monogdb syslog message
  --logappend                 append to logpath instead of over-writing
  --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)
  --keyFile arg               private key for cluster authentication
  --setParameter arg          Set a configurable parameter
  --httpinterface             enable http interface
  --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)
  --fork                      fork server process
  --auth                      run with security
  --noauth                    run without security
  --ipv6                      enable IPv6 support (disabled by default)
  --jsonp                     allow JSONP access via http (has security 
                              implications)
  --rest                      turn on simple rest api
  --slowms arg (=100)         value of slow for profile and console log
  --profile arg               0=off 1=slow, 2=all
  --cpu                       periodically show cpu and iowait utilization
  --sysinfo                   print some diagnostic system information
  --dbpath arg (=/data/db)    directory for datafiles - defaults to /data/db/
  --directoryperdb            each database will be stored in a separate 
                              directory
  --noIndexBuildRetry         don't retry any index builds that were 
                              interrupted by shutdown
  --noprealloc                disable data file preallocation - will often hurt
                              performance
  --nssize arg (=16)          .ns file size (in MB) for new databases
  --quota                     limits each database to a certain number of files
                              (8 default)
  --quotaFiles arg            number of files allowed per db, implies --quota
  --smallfiles                use a smaller default file size
  --syncdelay arg (=60)       seconds between disk syncs (0=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
  --noscripting               disable scripting engine
  --notablescan               do not allow table scans
  --journal                   enable journaling
  --nojournal                 disable journaling (journaling is on by default 
                              for 64 bit)
  --journalOptions arg        journal diagnostic options
  --journalCommitInterval arg how often to group/batch commit (ms)
  --shutdown                  kill a running server (for init scripts)


Replication options:
  --oplogSize arg       size to use (in MB) for replication op log. default is 
                        5% 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
  --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 [/]
  --replIndexPrefetch arg specify index prefetching behavior (if secondary) 
                          [none|_id_only|all]


Sharding options: ERROR: dbpath (/data/db) does not exist.
  --configsvr           declare this is a config db of a cluster; default port 
                        27019; default dir /data/configdbERROR: dbpath (/data/db) does not exist.
  --shardsvr            declare this is a shard db of a cluster; default port 
                        27018


看着有点乱 先讲究看吧    ^ _ ^

怎么启动呢    ,在启动时 有个参数叫 --dbpath 这个是指定数据文件的路径  你要是不指定呢,结果是这样的 ERROR: dbpath (/data/db) does not exist.  Create this directory or give existing directory in --dbp ,还是乖乖的指定吧,第一次启动比较慢 大家耐心等待就好啦。来个java喝喝。启动起来怎么关呢?mongod  --shutdwon 这个参数一般情况下不行,它还是取找默认目录 There doesn't seem to be a server running with dbpath: /data/db  ,所以你关数据库的时候也必须加上那个路径参数。这样你就可以把它关掉啦。

另外加上 --rest 网页才可以通过28017访问控制台。

2, mongoDB 里边有个默认的数据库test,里边有个默认的集合叫 foo.

当我们想插入一条数据时,这样就可已啦

首先运行 mongo  如后会出来一个shell 环境,你输入命令就行了。什么不知到有什么命令 help一下再说。

db.foo.insert({"usrname":"foo","userage":27})
WriteResult({ "nInserted" : 1 })  这样你就成功插入了一条数据。

db.foo.findOne({{"usrname":"foo"}}  如果有多条匹配结果的话,他只会显示第一条~_~。







你可能感兴趣的:(MongoDB)