首先要安裝mongodb,具體安裝過程參考菜鳥教程html
由於我是mac,因此如下內容以OS系統爲主,Windows系統建議參考 菜鳥教程
進入mongodb的bin文件目錄下,運行mongod執行文件node
sudo ./mongod //以管理員身份運行
而後另開一個命令行,一樣進入mongodb的bin文件目錄下,運行mongo執行文件,而後便會進入mongodb的shell環境mongodb
./mongo //進入mongodb的shell環境 >2+2 4
在mongodb的shell環境中能夠直接操做數據庫,語法請參考菜鳥教程
但shell操做比較反人類,我在這裏推薦mongodb的GUI軟件——Robo 3T,能夠自行在官網下載shell
在nodejs環境中我選擇的是mongoose
模塊數據庫
var mongoose=require('mongoose')
詳情請戳 mongoose官網
鏈接數據庫數組
mongoose.connect('mongodb://localhost:27017/test')//test即爲存儲的數據庫名稱,若是不存在將會自動生成
var CatSchema=mongoose.Schema({ name:String, age:Number }) var Cat=mongoose.model('Cat',CatSchema) //也能夠合二爲一,直接定義model var Cat=mongoose.model('Cat',{ name:String, age:Number }) //mongoose.model的第一個參數的字符串加上字母s即是儲存在的數據庫表單的名稱(Cats)
mongoose Schema經常使用預置類型:
var kitty=new Cat({ name:'Kitty', age:3 })
kitty.save(function(err,res){ if(err) console.error(err) else console.log(res)//res爲保存成功的對象 })
var where={ name:'Kitty' } var update={ age:4 } Cat.update(where,update,function(err,res){ if(err) console.error(err) else console.log(res) })
經過ID查找並更新的方法mongoose
Cat.findByIdAndUpdate(whereById,update,function(err,res)){ if(err) console.error(err) else console.log(res) })
Cat.remove(where,function(err,res)) //經過ID查找並刪除 Cat.findByIdAndRomove(where,function(err,res))
Cat.find(where,function(err,res))//res 返回查找到的對象數組 //能夠限定輸出的內容 var opt={ name:1//選擇輸出的值爲1,不輸出的值爲0(其餘不指定默認爲0) } Cat.find(where,opt,function(err,res)) //var where=_id Cat.findById(where,function(err,res))//res 輸出查詢到的對象
Cat.count(where,function(err,res))//res輸出查詢數量