关于MongoDB的笔记
中文的目的
我想要大概了解MongoDB。
下载
由于我想在CentOS6上轻松尝试,所以需要下载二进制文件。
https://www.mongodb.org/dl/linux/x86_64-rhel62
MongoDB的文件结构
$ tree .
.
├── GNU-AGPL-3.0
├── MPL-2
├── README
├── THIRD-PARTY-NOTICES
└── bin
├── bsondump
├── mongo
├── mongod
├── mongodump
├── mongoexport
├── mongofiles
├── mongoimport
├── mongooplog
├── mongoperf
├── mongorestore
├── mongos
├── mongosniff
├── mongostat
└── mongotop
启动mongod
$ mkdir -p ./data/db
$ ./bin/mongod -dbpath data/db
MongoDB的数据结构
データベースはMySQLでいうところのデータベースで、Collectionはテーブル相当でしょうか。Documentは行相当だけどスキーマレスであるところがRDBとは違う。primary keyは”_id”あたり?
MongoDB/
├── Database1
│ ├── Collection1
│ │ ├── Document1
│ │ └── Document2
│ └── Collection2
│ ├── Document1
│ └── Document2
└── Database2
├── Collection1
│ ├── Document1
│ └── Document2
└── Collection2
├── Document1
└── Document2
---------------
> var c = db.col1.find()
> while(c.hasNext())printjson(c.next())
{ "_id" : ObjectId("584396e96516646a4dfeab45"), "name" : "mongo" }
{
"_id" : ObjectId("584397126516646a4dfeab46"),
"string" : "hello",
"array" : [
"sun",
"mon",
"tue"
]
}
{ "_id" : ObjectId("584398486516646a4dfeab47"), "name" : "hogehoge" }
{ "_id" : ObjectId("584399996516646a4dfeab48"), "x" : 4, "j" : 1 }
{ "_id" : ObjectId("584399996516646a4dfeab49"), "x" : 4, "j" : 2 }
{ "_id" : ObjectId("584399996516646a4dfeab4a"), "x" : 4, "j" : 3 }
与客户端连接
$ ./bin/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 : 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
指令
使用client进行连接
以中文进行本地化的改写,只需提供一种选项:
mongo [服务器地址]/[数据库名称]
$ ./bin/mongo localhost/testdb
MongoDB shell version: 3.2.11
connecting to: localhost/testdb
数据库操作
DB切り替え・作成
$ use [DB名]
DB削除
$ use [DB名]
db.dropDatabase()
{ "ok" : 1 }
DB一覧
$ show dbs
收藏操作
在MySQL中,它就相当于一个数据表。
一覧
use [DB名]
show collections
コレクション作成
use [DB名]
db.createCollection("col1")
{ "ok" : 1 }
コレクション削除
use [DB名]
db.col1.drop()
TAB填写完整
方便。
db.drop
db.dropAllRoles( db.dropAllUsers( db.dropDatabase( db.dropRole( db.dropUser(
当出现”not master and slaveOk=false”时。
db.getMongo().setSlaveOk()
请用中文参考
-
MongoDBでゆるふわDB体験
Introduction to MongoDB