前言html
筆者寫這個博客主要是參考菜鳥網站runoob.com,是爲了想快速學習瞭解MongoDB的一些基本知識,若是你想深刻了解,推薦MongDB Mnaual系統學習MongDB.linux
一、簡介sql
MongDB是開源的文檔存儲類型數據庫。
mongodb
二、安裝啓動shell
# curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.0.6.tgz數據庫
# tar -zxvf mongodb-linux-x86_64-3.0.6.tgzbash
# mv mongodb-linux-x86_64-3.0.6 /usr/local/mongodb/app
# mkdir -p /usr/local/mongodb/data/dbless
# cat /etc/mongod.confcurl
[root@sht-sgmhadoopcm-01 mongodb]# cat /etc/mongod.conf systemLog: destination: file path: "/usr/local/mongodb/log/mongod.log" logAppend: true storage: dbPath: /usr/local/mongodb/data/db journal: enabled: true processManagement: fork: true pidFilePath: /usr/local/mongodb/data/db/mongod.pid net: port: 27017 bindIp: 0.0.0.0 setParameter: enableLocalhostAuthBypass: false
# bin/mongod --config /etc/mongod.conf
warning: bind_ip of 0.0.0.0 is unnecessary; listens on all ips by default
about to fork child process, waiting until server is ready for connections.
forked process: 21394
child process started successfully, parent exiting
# bin/mongo
> db.runoob.insert({x:10})
WriteResult({ "nInserted" : 1 })
> db.runoob.find()
{ "_id" : ObjectId("5bd2c9e8c0e1c2a4634de8bb"), "x" : 10 }
三、MongoDB基本概念
(1) 基本結構(與MySQL對比)
MongDB--db--collection--document--field
MySQL--db--table--row--column
[root@sht-sgmhadoopcm-01 mongodb]# bin/mongo
MongoDB shell version: 3.0.6
connecting to: test
list全部db
> show dbs
local 0.078GB
test 0.078GB
查看當前在哪一個db下
> db
test
切換db
> use local
switched to db local
(2)ObjectId
ObjectId 相似惟一主鍵,能夠很快的去生成和排序,包含 12 bytes,含義是:
前 4 個字節表示建立unix時間戳,格林尼治時間UTC時間,比北京時間晚了8小時
接下來的3個字節是機器標識碼
緊接的兩個字節由進程id組成PID
最後三個字節是隨機數
這裏表示的時間是UTC時間
> var newobject = ObjectId()
> newobject.getTimestamp()
ISODate("2018-10-26T08:47:59Z")
> newobject.str
5bd2d4bf6d79d6dd6eeb51b9
(3)時間函數
> var mydate1=new Date() #UTC時間
> mydate1
ISODate("2018-10-26T08:54:15.997Z")
> typeof mydate1
object
> var mydate2=ISODate() #UTC時間
> mydate2
ISODate("2018-10-26T08:55:45.199Z")
> typeof mydate2
object
返回一個時間類型的字符串
> var mydate1str = mydate1.toString()
> typeof mydate1str
string
> Date() #UTC+8
Fri Oct 26 2018 16:56:48 GMT+0800 (CST)
> ISODate()
ISODate("2018-10-26T08:57:04.144Z")
四、MongDB基本操做
(1)建立,刪除DB
在MongoDB中,集合只有在內容插入後纔會真正的建立
> use runoob
switched to db runoob
> db
runoob
> show dbs
local 0.078GB
test 0.078GB
> db.runoob.insert({"name":"jian"})
WriteResult({ "nInserted" : 1 })
> show dbs
local 0.078GB
runoob 0.078GB
test 0.078GB
> show dbs
local 0.078GB
runoob 0.078GB
test 0.078GB
刪除DB
> db.dropDatabase()
{ "dropped" : "runoob", "ok" : 1 }
> show dbs
local 0.078GB
test 0.078GB
(2)建立、刪除collection
> use test
switched to db test
> db.createCollection("collection1")
{ "ok" : 1 }
> show collections
collection1
runoob
system.indexes
建立固定大小,自動在 _id字段上建立索引,document數量爲10000;
> db.createCollection("collection2", {capped:true, autoIndexId:true, size:6142800, max:10000})
{ "ok" : 1 }
在 MongoDB 中,你不須要建立集合。當你插入一些文檔時,MongoDB 會自動建立集合
> db.collection3.insert({"key":"values"})
WriteResult({ "nInserted" : 1 })
> show tables
collection1
collection2
collection3
runoob
system.indexes
刪除collection
> db.collection3.drop()
true
(3)插入,更新,刪除document
a.插入document
>db.collection1.insert({title: 'MongoDB 教程', description: 'MongoDB 是一個 Nosql 數據庫', by: '菜鳥教程', url: 'http://www.runoob.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 }) > db.collection1.find() 經過定義個document變量來插入數據 >document_example=({title: 'Oracle 教程', description: 'Oracle 是一個 RDBMS 數據庫', by: '菜鳥教程', url: 'http://www.runoob.com', tags: ['Oracle', 'database', 'RDBMS'], likes: 100 }) > db.collection1.insert(document_example) WriteResult({ "nInserted" : 1 })
b.更新document
修改匹配的第一條title內容 > db.collection1.update({'title':'MongoDB 教程'},{$set:{'title':'MongoDB'}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.collection1.find().pretty() 修改匹配整個集合的title內容 db.collection1.update({'title':'MongoDB 教程'},{$set:{'title':'MongoDB'}},{multi:true}) 根據_id更新id爲56064f89ade2f21f36b03136 的文檔數據: db.collection1.save({ "_id" : ObjectId("5bd81c443927ce142a81ff08"), "title" : "MongoDB", "description" : "MongoDB 是一個 Nosql 數據庫", "by" : "Runoob", "url" : "http://www.runoob.com", "tags" : [ "mongodb", "NoSQL" ], "likes" : 110 })
c.刪除document
刪除title爲MongoDB的全部document記錄
> db.collection1.remove({'title':'MongoDB'})
刪除title爲MongoDB的一個document記錄
> db.collection1.remove({'title':'MongoDB 教程'},{justOne:1})
清空集合,刪除全部的document
> db.collection1.remove({})
(4)查詢find()
易讀方式查詢
> db.collection1.find().pretty()
指定條件查詢docuemnt,返回全部知足條件的記錄
> db.collection1.find({"title" : "Oracle 教程"})
指定條件查詢docuemnt,返回第一條知足條件的記錄
> db.collection1.findOne({"likes" : 100})
(5)一些經常使用的操做符
指定likes小於100的,
$gt -- greater than >
$gte -- gt equal >=
$lt -- less than <
$lte -- lt equal <=
$ne -- not equal !=
$eq -- equal =
> db.collection1.find({"likes":{$lt:100}})
and條件
> db.collection1.find({"title" : "MongoDB 教程","likes":{$gt:100}})
or條件
> db.collection1.find({$or:[{"likes":{$lt:90}},{"likes":{$gt:100}}]})
經過$type指定數據類型,2表示string類型的數據
> db.collection1.find({"title":{$type:2}})
limit(N)和skip(N)
> db.collection1.find().limit(3)
> db.collection1.find({},{"_id":0,"title":1,"url":1}).limit(2)
skip(N)跳過前三行,直接返回第四行及之後docuemnt
> db.collection1.find({},{"_id":0,"title":1,"url":1}).skip(3)
排序sort(),1爲升序,-1爲倒序
> db.collection1.find({},{"_id":0,"title":1,"likes":1}).sort({"likes":1})
> db.collection1.find({},{"_id":0,"title":1,"likes":1}).sort({"likes":-1})
(6)MongoDB索引createIndex()
建立單列索引
> db.collection1.createIndex({"title":1})
建立多列索引
> db.collection1.createIndex({"title":1,"likes":-1})
建立惟一索引
> db.collection1.createIndex({"_id":1},{unique:true})
(7)聚合函數aggregate()
> db.coll1.find() { "_id" : ObjectId("5bdb130c28a4a2aea6e37dcf"), "title" : "MongoDB Overview", "description" : "MongoDB is no sql database", "by_user" : "runoob.com", "url" : "http://www.runoob.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } { "_id" : ObjectId("5bdb130c28a4a2aea6e37dd0"), "title" : "NoSQL Overview", "description" : "No sql database is very fast", "by_user" : "runoob.com", "url" : "http://www.runoob.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 10 } { "_id" : ObjectId("5bdb130c28a4a2aea6e37dd1"), "title" : "Neo4j Overview", "description" : "Neo4j is no sql database", "by_user" : "Neo4j", "url" : "http://www.neo4j.com", "tags" : [ "neo4j", "database", "NoSQL" ], "likes" : 750 } > db.coll1.aggregate([{$group : {_id : "$by_user", count : {$sum : 1}}}]) { "_id" : "Neo4j", "count" : 1 } { "_id" : "runoob.com", "count" : 2 } > db.coll1.aggregate([{$group : {_id : "$by_user", count : {$sum : "$likes"}}}]) { "_id" : "Neo4j", "count" : 750 } { "_id" : "runoob.com", "count" : 110 } 管道操做 > db.coll1.aggregate({ $project : {_id:0,title : 1 ,likes:10}}) { "title" : "MongoDB Overview", "likes" : 100 } { "title" : "NoSQL Overview", "likes" : 10 } { "title" : "Neo4j Overview", "likes" : 750 } $likes用於獲取大於70小於或等於200記錄,而後將符合條件的記錄送到下一階段$group管道操做符進行處理。 > db.coll1.aggregate( [{ $match : { likes : { $gt : 70, $lte : 200 } } },{ $group: { _id: null, count: { $sum: 1 } } }] ); { "_id" : null, "count" : 1 }
參考連接