準(zhǔn)備
npm install mongodb /*安裝mongodb模塊*/
一些mongodb命令
show dbs //展示所有數(shù)據(jù)庫(kù)
use db //使用該數(shù)據(jù)庫(kù),未創(chuàng)建則直接創(chuàng)建
db.documents.drop() //刪除該collection中所有數(shù)據(jù)(或者使用.remove()通過(guò)條件刪除)
db.documents.find() //查詢?cè)揷ollection中所有數(shù)據(jù)
連接mongodb
/*app.js*/
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
/*assert模塊用于編寫(xiě)程序的單元測(cè)試用例*/
// Connection URL
var url = 'mongodb://localhost:27017/elys';/*請(qǐng)求url*/
// 通過(guò)mongodb提供的connect方法來(lái)連接數(shù)據(jù)庫(kù)
MongoClient.connect(url, function(err, db) { /*這里的db便是連接成功的mongodb*/
assert.equal(null, err);/*表達(dá)式不符合時(shí)輸出err*/
console.log("Connected correctly to server");
db.close();
});
插入數(shù)據(jù)
/*新增一個(gè)用于插入數(shù)據(jù)的方法*/
var insertDocuments = function (db, callback){
var collection = db.collection('documents')/*獲取collection*/
collection.insertMany([/*操作語(yǔ)句*/
{a:1}, {a:2}, {a:3}/*提供的數(shù)據(jù)*/
], function(err, result){/*回調(diào)*/
assert.equal(err, null)
assert.equal(3, result.result.n) /*檢查結(jié)果行為等(是不是真的3個(gè))*/
assert.equal(3, result.ops.length)
console.log("Inserted 3 documents into the document collection")
callback(result) /*返回結(jié)果*/
})
}
/*修改后的app.js*/
//...
console.log("Connected correctly to server");
/*調(diào)用該方法*/
insertDocuments(db, function(){
db.close();
})
//...
更新數(shù)據(jù)
var updateDocument = function (db, callback){
var collection = db.collection('documents')
collection.updateOne({ a: 2 },{ $set: {b:1}}, function(err, result){
/*mongodb提供許多api,updateOne()是其中之一*/
assert.equal(err, null)
assert.equal(1, result.result.n)
console.log("Updated the document with thie field a equal to 2")
callback(result)
})
}
/*修改后的app.js*/
//...
console.log("Connected correctly to server");
/*調(diào)用該方法*/
insertDocuments(db, function(){
updateDocument(db, function(){
db.close();
})
})
//...
刪除數(shù)據(jù)
var deleteDocument = function(db, callback){
var collection = db.collection('documents')
collection.deleteOne({a:3}, function(err, result){
assert.equal(err, null)
assert.equal(1, result.result.n)
console.log("Remove the document with the field a equal to 3")
callback(result)
//console.log(result)
})
}
/*修改后的app.js*/
//...
console.log("Connected correctly to server");
/*調(diào)用該方法*/
insertDocuments(db, function(){
updateDocument(db, function(){
deleteDocument(db, function(){
db.close();
})
})
})
//...
查詢數(shù)據(jù)
var findDocuments = function(db, callback){
var collection = db.collection('documents')
collection.find({}).toArray(function(err, docs){
assert.equal(err, null)
assert.equal(2, docs.length)
console.log("Found the following records")
console.dir(docs)
callback(docs)
})
}
/*修改后的app.js*/
//...
console.log("Connected correctly to server");
/*調(diào)用該方法*/
insertDocuments(db, function(){
updateDocument(db, function(){
deleteDocument(db, function(){
findDocuments(db, function(){
db.close();
})
})
})
})
//...
參考
https://github.com/mongodb/node-mongodb-native
未完待續(xù)