安裝
我這是Mac系統(tǒng),直接選擇brew安裝就行了
brew install mongodb
[圖片上傳中...(image-20190601111727872.png-b280ab-1559898653894-0)]
然后運行
mongod
不過,上面運行是在前臺,當關閉終端后就會停止??梢酝ㄟ^設置配置文件,使其保持在后臺運行。
mongod --dbpath=/data/db --logpath=/usr/local/var/lomongodb/mongo.log --logappend --fork
使用
1、連接數(shù)據(jù)庫
第一種方式
首先,連接數(shù)據(jù)庫
$ mongo 192.168.31.87:27017
如果設置了密碼,則解開授權
> db.auth("root", “password”)
第二種方式:
$ mongo 192.168.31.87 --port 27017 -u root -p --authenticationDatabase admin
參考:http://www.itdecent.cn/p/79caa1cc49a5
在這里,我遇到了問題,使用mongo --port 27017 -u root -p ,然后輸入密碼是不行的
2、創(chuàng)建數(shù)據(jù)庫
> use test
如果數(shù)據(jù)庫存在,則切換到此數(shù)據(jù)庫;如果不存在,則創(chuàng)建數(shù)據(jù)庫并切換到此數(shù)據(jù)庫
> db
test
上面命令會顯示當前使用的數(shù)據(jù)庫
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
上面命令會顯示有哪些數(shù)據(jù)庫,當插入一條數(shù)據(jù)后,就會顯示出test庫
3、集合
Mongodb中的集合,相當于Mysql中的表。創(chuàng)建集合使用createCollection()方法,格式:
db.createCollection(name, options)
參數(shù)說明:
- name: 要創(chuàng)建的集合名稱
- options: 可選參數(shù),指定有關內(nèi)存大小及索引的選項
option 有如下參數(shù):

在插入文檔時,MongoDB首先檢查固定集合的size字段,然后檢查max字段
1、創(chuàng)建集合
> db.createCollection("test")
{ "ok" : 1 }
> db.createCollection("col", {capped: true, autoIndexId: true, size: 8000000, max:100})
{
"note" : "the autoIndexId option is deprecated and will be removed in a future release",
"ok" : 1
}
# 插入文檔時,會自動創(chuàng)建集合
> db.student.insert({"name": "jack"})
WriteResult({ "nInserted" : 1 })
2、顯示當前數(shù)據(jù)庫下的集合
> show collections
col
student
test
3、刪除集合
> db.col.drop()
true
> show collections
student
test
4、文檔
MongoDB中的文檔就相當于Mysql中的一條記錄。文檔的數(shù)據(jù)結構和JSON基本一樣。
1、插入文檔
MongoDB使用insert()或save()方法向集合中插入文檔,語法如下:
db.collection.insert(document)
具體實踐如下:
> db.test.insert({"name":"Jack", "height": 1.78})
WriteResult({ "nInserted" : 1 })
2、查詢文檔
查詢使用的是find()方法,語法:
db.collection.find(query, projection)
- query: 可選,使用查詢操作符指定查詢條件
- projection: 可選,使用投影操作符指定返回的鍵
如果需要易讀的方式來讀取數(shù)據(jù),可以使用pretty()方法,使用如下:
db.collection.find().pretty()
具體實踐如下:
> db.test.find()
{ "_id" : ObjectId("5cf1f122e3f016c5abfb73c3"), "name" : "Jack", "height" : 1.78 }
> db.test.find().pretty()
{
"_id" : ObjectId("5cf1f122e3f016c5abfb73c3"),
"name" : "Jack",
"height" : 1.78
}
> db.test.find({'name': 'Jack'}).pretty()
{
"_id" : ObjectId("5cf1f122e3f016c5abfb73c3"),
"name" : "Jack",
"height" : 1.78
}
3、更新文檔
5 備份數(shù)據(jù)
mongodump -h 192.168.31.87 -d xqxd_data -u root --authenticationDatabase admin