mongoDB 作為非關(guān)系型數(shù)據(jù)庫(kù)镜会,采用類(lèi)似json的結(jié)構(gòu)保存數(shù)據(jù),json和js更配哦~
庫(kù)名:guolei
table名: col
數(shù)據(jù): 三個(gè)對(duì)象({name:'',id:''})
安裝
brew install mongodb
開(kāi)啟服務(wù)
需要權(quán)限,因?yàn)閙ongodb 安裝在/data/db下终抽,需要權(quán)限才能創(chuàng)建訪問(wèn)
sudo mongod
操作數(shù)據(jù)庫(kù)
1 首先戳表,新建一個(gè)命令行 ctrl+n
進(jìn)入mongo環(huán)境
mongod
2 創(chuàng)建一個(gè)數(shù)據(jù)庫(kù),名字是'guolei'
use guolei
可以通過(guò)
show dbs
查看數(shù)據(jù)庫(kù)列表(如果看不到自己創(chuàng)建的數(shù)據(jù)庫(kù),需要插入數(shù)據(jù))
3 新增數(shù)據(jù)
數(shù)據(jù)表的名字叫'demo'
db.demo.insert({name:'guolei'})
4 ***查看數(shù)據(jù)表****
db.demo.find().pretty()
pretty是組織化的方式返回昼伴,更容易閱讀匾旭,不加也行。
5 修改數(shù)據(jù)
假如要把我的名字改成guanxi,執(zhí)行
db.demo.update({name:'guolei'},{$set:{'title':'guanxi'}})
6 刪除
增刪改查圃郊。价涝。。持舆。
db.demo.remove({'title':'guanxi'})
實(shí)際操作如下
備注: 可以使用Robomongodb這款可視化工具 操作數(shù)據(jù)庫(kù)
node環(huán)境使用MongoDB
新建一個(gè)目錄飒泻,初始化
git init
安裝Mongodb模塊
npm install mongodb
新建一個(gè)index.js
var mongodb = require('mongodb');
var server = new mongodb.Server('localhost', 27017, {});
var db = new mongodb.Db('mydb', server, {});
//連接db
db.open(function(err, db){
if(!err){
console.log('connect db');
db.createCollection('mycoll', {}, function(err, collection){
if(err){
console.log(err);
}else{
var tmp1 = {title:'hello'};
var tmp2 = {title:'world'};
collection.insert([tmp1,tmp2],{safe:true},function(err,result){
console.log(result);
});
collection.find().toArray(function(err,docs){
console.log('find');
console.log(docs);
});
collection.findOne(function(err,doc){
console.log('findOne');
console.log(doc);
});
}
});
}else{
console.log(err);
}
});
最后執(zhí)行
node index.js
注意
- 保證mongod 運(yùn)行著
- node版本>4
執(zhí)行結(jié)果
代碼:github.com/thunderqin/mongo
寫(xiě)這篇文章的時(shí)候鞭光,本人已經(jīng)喝了四瓶啤酒,不詳細(xì)的地方泞遗,大家海涵。席覆。史辙。。
著作權(quán)聲明
本文demo借鑒了whoamme的博客
原文地址: 覃國(guó)雷的博客