MongoDB簡單使用

一、介紹

MongoDB 是一個高性能分布式文件存儲數(shù)據(jù)庫侄榴,通常采用官方的二進制包進行安裝.

二、MongoDB 安裝

  • 使用官網(wǎng)二進制包安裝 (根據(jù)系統(tǒng)選擇對應的版本)
wget -c https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.2.8.tgz     -c 選項斷點續(xù)傳
tar -zxvf mongodb-linux-x86_64-3.2.8.tgz
mv mongodb-linux-x86_64-3.2.8  /web/mongodb      //復制到指定目錄即可
cd /web/mongodb    
mkdir mongodb_db  //創(chuàng)建數(shù)據(jù)庫存放位置
/web/mongodb/bin/mongod --dbpath=/web/mongodb/mongodb_db/
指定數(shù)據(jù)庫
在另一個終端打開mongodb
/web/mongodb/bin/mongo
出現(xiàn)如下网沾,則說明OK   
2016-04-13T06:58:53.672-0400 I CONTROL  [initandlisten] ** ......
  • MongoDB服務加入隨機啟動
vi /etc/rc.local
  • 使用vi編輯器打開配置文件癞蚕,并在其中加入下面一行代碼
/web/mongodb/bin/mongod -dbpath=/usr/local/mongodb/data/db --port 27017 -logpath=/usr/local/mongodb/log --logappend
  • MongoDB服務客戶端加入環(huán)境變量
ln -s /web/ mongodb/bin/mongo  /usr/bin/ mongo
  • 執(zhí)行mongod啟動MongoDB服務器指定配置文件
/web/mongodb/bin/mongod --config mongodb.conf

三、mongodb和關系型數(shù)據(jù)庫的對比圖

對比項 mongodb MySQL oracle
集合list 二維表table
表的一行數(shù)據(jù) 文檔document 一條記錄record
表字段 鍵key 字段field
字段值 值value 值value
主外鍵 PK,FK
靈活度擴展性 極高

四 辉哥、基本SHELL命令

創(chuàng)建一個數(shù)據(jù)庫
use [dbname] //此時你什么也沒有處理就離開則這個空數(shù)據(jù)庫會被刪除
給指定數(shù)據(jù)庫添加集合并且添加記錄
db.[documentname].insert({name:"zhangsan"}); //自動創(chuàng)建一個文檔ID
查看所有數(shù)據(jù)庫
show dbs //默認提供本地數(shù)據(jù)
查看數(shù)據(jù)庫中的所有文檔
show collections
官方文檔:https://docs.mongodb.com/manual/crud/

五桦山、 插入

1.db.collection.insert()
2.db.collection.insertOne() New in version 3.2
3.db.collection.insertMany() New in version 3.2
crud-annotated-mongodb-insert.png

1、db.collection.insert()

  • 插入一個文檔沒有指定一個_id字段
    db.products.insert( { item: "card", qty: 15 } )
    備注:在插入期間,mongod將創(chuàng)建_id領域并為其分配一個獨一無二的ObjectId的文檔ID
    { "_id" : ObjectId("5063114bd386d8fadbd6b004"), "item" : "card", "qty" : 15 }
  • 插入一個文檔指定一個_id字段
    db.products.insert( { _id: 10, item: "box", qty: 20 } )
    { "_id" : 10, "item" : "box", "qty" : 20 }
  • 一次插入多條醋旦,使用數(shù)組對象
db.products.insert(
   [
     { _id: 11, item: "pencil", qty: 50, type: "no.2" },
     { item: "pen", qty: 20 },
     { item: "eraser", qty: 25 }
   ]
{ "_id" : 11, "item" : "pencil", "qty" : 50, "type" : "no.2" }
{ "_id" : ObjectId("51e0373c6f35bd826f47e9a0"), "item" : "pen", "qty" : 20 }
{ "_id" : ObjectId("51e0373c6f35bd826f47e9a1"), "item" : "eraser", "qty" : 25 }

2恒水、db.collection.insertOne() New in version 3.2.

  • 插入一個文檔沒有指定一個_id字段
try {
   db.products.insertOne( { item: "card", qty: 15 } );
} catch (e) {
   print (e);
};
  • 插入一個文檔指定一個_id字段
try {
   db.products.insertOne( { _id: 10, item: "box", qty: 20 } );
} catch (e) {
   print (e);
}
  • 插入一個重復的索引值將拋出一個異常。
try {
   db.products.insertOne( { _id: 10, "item" : "packing peanuts", "qty" : 200 } );
} catch (e) {
   print (e);
}
//錯誤提示
WriteError({
   "index" : 0,
   "code" : 11000,
   "errmsg" : "E11000 duplicate key error collection: inventory.products index: _id_ dup key: { : 10.0 }",
   "op" : {
      "_id" : 10,
      "item" : "packing peanuts",
      "qty" : 200
   }
})

3饲齐、db.collection.insertMany() New in version 3.2.

  • 插入一個文檔沒有指定一個_id字段
try {
   db.products.insertMany( [
      { item: "card", qty: 15 },
      { item: "envelope", qty: 20 },
      { item: "stamps" , qty: 30 }
   ] );
} catch (e) {
   print (e);
}
//輸出
{
   "acknowledged" : true,
   "insertedIds" : [
      ObjectId("562a94d381cb9f1cd6eb0e1a"),
      ObjectId("562a94d381cb9f1cd6eb0e1b"),
      ObjectId("562a94d381cb9f1cd6eb0e1c")
   ]
}
  • 插入一個文檔指定一個_id字段
try {
   db.products.insertMany( [
      { _id: 10, item: "large box", qty: 20 },
      { _id: 11, item: "small box", qty: 55 },
      { _id: 12, item: "medium box", qty: 30 }
   ] );
} catch (e) {
   print (e);
}
//輸出
{ "acknowledged" : true, "insertedIds" : [ 10, 11, 12 ] }

六钉凌、查詢

db.collection.find()

在插入示例文檔之前使用db.users.drop()刪除,避免相同文檔ID沖突捂人。


crud-annotated-mongodb-find.png
db.users.insertMany(
  [
     {
       _id: 1,
       name: "sue",
       age: 19,
       type: 1,
       status: "P",
       favorites: { artist: "Picasso", food: "pizza" },
       finished: [ 17, 3 ],
       badges: [ "blue", "black" ],
       points: [
          { points: 85, bonus: 20 },
          { points: 85, bonus: 10 }
       ]
     },
     {
       _id: 2,
       name: "bob",
       age: 42,
       type: 1,
       status: "A",
       favorites: { artist: "Miro", food: "meringue" },
       finished: [ 11, 25 ],
       badges: [ "green" ],
       points: [
          { points: 85, bonus: 20 },
          { points: 64, bonus: 12 }
       ]
     },
     {
       _id: 3,
       name: "ahn",
       age: 22,
       type: 2,
       status: "A",
       favorites: { artist: "Cassatt", food: "cake" },
       finished: [ 6 ],
       badges: [ "blue", "red" ],
       points: [
          { points: 81, bonus: 8 },
          { points: 55, bonus: 20 }
       ]
     },
     {
       _id: 4,
       name: "xi",
       age: 34,
       type: 2,
       status: "D",
       favorites: { artist: "Chagall", food: "chocolate" },
       finished: [ 5, 11 ],
       badges: [ "red", "black" ],
       points: [
          { points: 53, bonus: 15 },
          { points: 51, bonus: 15 }
       ]
     },
     {
       _id: 5,
       name: "xyz",
       age: 23,
       type: 2,
       status: "D",
       favorites: { artist: "Noguchi", food: "nougat" },
       finished: [ 14, 6 ],
       badges: [ "orange" ],
       points: [
          { points: 71, bonus: 20 }
       ]
     },
     {
       _id: 6,
       name: "abc",
       age: 43,
       type: 1,
       status: "A",
       favorites: { food: "pizza", artist: "Picasso" },
       finished: [ 18, 12 ],
       badges: [ "black", "blue" ],
       points: [
          { points: 78, bonus: 8 },
          { points: 57, bonus: 7 }
       ]
     }
  ]
)
  • 集合中的所有文檔
    db.users.find() //db.users.find().toArray() //轉(zhuǎn)數(shù)組形式
  • 指定條件查詢
  • 用戶集合所有文件status字段值為"A" db.users.find( { status: "A" } )
  • 查詢操作符
比較運算符
Name 符號 Description 案例
$eq = 匹配值等于指定值 db.inventory.find( { qty: { $eq: 20 } } ) ; db.inventory.find( { qty: 20 } ) ; db.inventory.find( { tags: { $eq: [ "A", "B" ] } } ) ; db.inventory.find( { tags: [ "A", "B" ] } )
$gt > 匹配值大于指定值 db.inventory.find( { qty: { $gt: 20 } } )
$gte >= 匹配值大于或等于指定值 db.inventory.find( { qty: { $gte: 20 } } )
$lt < 匹配值小于指定值 db.inventory.find( { qty: { $lt: 20 } } )
$lte <= 匹配值小于或等于指定值 db.inventory.find( { qty: { $lte: 20 } } )
$ne != 匹配所有的值不等于指定值 db.inventory.find( { qty: { $ne: 20 } } )
$in exist 匹配任何一個數(shù)組中指定的值 db.inventory.find( { qty: { $in: [ 5, 15 ] } } ) ; db.inventory.find( { tags: { $in: [ /^be/, /^st/ ] } } )
$nin not exist 匹配出不在數(shù)組中指定的值 db.inventory.find( { qty: { $nin: [ 5, 15 ] } } )
邏輯運算符
Name 符號 Description 案例
$or OR 邏輯或 db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } ) ; db.inventory.find ( { quantity: { $in: [20, 50] } } )
$and AND 邏輯與 db.inventory.find( { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } } ] } ) ; db.inventory.find( { price: { $ne: 1.99, $exists: true } } )
$not NOT 不在范圍內(nèi) db.inventory.find( { price: { $not: { $gt: 1.99 } } } )
$nor NOR 不存在 db.inventory.find( { $nor: [ { price: 1.99 }, { sale: true } ] } )

詳細使用官方文檔: https://docs.mongodb.com/manual/reference/operator/query/

七御雕、修改

db.collection.update()
crud-annotated-mongodb-update.png
db.collection.update()
db.collection.updateOne() New in version 3.2
db.collection.updateMany() New in version 3.2
db.collection.replaceOne() New in version 3.2

八矢沿、刪除

db.collection.remove()
crud-annotated-mongodb-remove.png
db.collection.remove()
db.collection.deleteOne() New in version 3.2
db.collection.deleteMany() New in version 3.2
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市饮笛,隨后出現(xiàn)的幾起案子咨察,更是在濱河造成了極大的恐慌论熙,老刑警劉巖福青,帶你破解...
    沈念sama閱讀 219,039評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異脓诡,居然都是意外死亡无午,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評論 3 395
  • 文/潘曉璐 我一進店門祝谚,熙熙樓的掌柜王于貴愁眉苦臉地迎上來宪迟,“玉大人,你說我怎么就攤上這事交惯〈卧螅” “怎么了?”我有些...
    開封第一講書人閱讀 165,417評論 0 356
  • 文/不壞的土叔 我叫張陵席爽,是天一觀的道長意荤。 經(jīng)常有香客問我,道長只锻,這世上最難降的妖魔是什么玖像? 我笑而不...
    開封第一講書人閱讀 58,868評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮齐饮,結(jié)果婚禮上捐寥,老公的妹妹穿的比我還像新娘。我一直安慰自己祖驱,他們只是感情好握恳,可當我...
    茶點故事閱讀 67,892評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著捺僻,像睡著了一般睡互。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上陵像,一...
    開封第一講書人閱讀 51,692評論 1 305
  • 那天就珠,我揣著相機與錄音,去河邊找鬼醒颖。 笑死妻怎,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的泞歉。 我是一名探鬼主播逼侦,決...
    沈念sama閱讀 40,416評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼匿辩,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了榛丢?” 一聲冷哼從身側(cè)響起铲球,我...
    開封第一講書人閱讀 39,326評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎晰赞,沒想到半個月后稼病,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,782評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡掖鱼,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,957評論 3 337
  • 正文 我和宋清朗相戀三年然走,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片戏挡。...
    茶點故事閱讀 40,102評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡芍瑞,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出褐墅,到底是詐尸還是另有隱情拆檬,我是刑警寧澤,帶...
    沈念sama閱讀 35,790評論 5 346
  • 正文 年R本政府宣布妥凳,位于F島的核電站竟贯,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏猾封。R本人自食惡果不足惜澄耍,卻給世界環(huán)境...
    茶點故事閱讀 41,442評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望晌缘。 院中可真熱鬧齐莲,春花似錦、人聲如沸磷箕。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽岳枷。三九已至芒填,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間空繁,已是汗流浹背殿衰。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留盛泡,地道東北人闷祥。 一個月前我還...
    沈念sama閱讀 48,332評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像傲诵,于是被迫代替她去往敵國和親凯砍。 傳聞我的和親對象是個殘疾皇子箱硕,可洞房花燭夜當晚...
    茶點故事閱讀 45,044評論 2 355

推薦閱讀更多精彩內(nèi)容