MongoDB是一种文档导向数据库管理系统,由C++撰写而成。
var MongoClient = require('mongodb').MongoClient;
var mongoHost = 'mongodb://127.0.0.1:27017/TestMongo';
MongoClient.connect(mongoHost,{ useNewUrlParser: true },function (err,dbManager) {
if (err) { throw err};
var dbopener = dbManager.db('TestMongo');
createTable('TESTTABLE',dbopener,dbManager);
});
function createTable(tableName,db,dbManager){
db.createCollection(tableName, function (err, res) {
if (err) throw err;
console.log("创建集合!");
var json ={'name':'张辉','age':'30'};
insertOneDataToMongo(db,dbManager,json);
var jsonData = [{'name':'张辉','age':'30'},{'name':'李辉','age':'30'},{'name':'王辉','age':'30'}];
insertMoreDataTOMongo(db,dbManager,jsonData);
var query = {'name':'张辉'};
queryDataFromMongo(query,db,dbManager);
var updateData = {$set: { "age" : "40" }};
updateDataFromMongo(query,updateData,db,dbManager);
updateMoreDataFromMongo(query,updateData,db,dbManager);
// deleteOneData(query,db,dbManager);
//deleteMoreData(query,db,dbManager);
var sort ={type: 1};
queryDataVisaSort(query,sort,db,dbManager);
queryPage(2,query,2,db,dbManager);
dbManager.close();
});
};
//插入单条数据
function insertOneDataToMongo(dbopener,dbManager,data){
dbopener.collection('TESTTABLE').insertOne(data,function(err,res){
if (err) {throw err};
console.log('数据插入成功');
dbManager.close();
});
};
//插入多条数据
function insertMoreDataTOMongo(dbopener,dbManager,data){
dbopener.collection('TESTTABLE').insertMany(data,function(err,res){
if (err) {throw err};
console.log('数据插入成功');
dbManager.close();
});
}
//查询数据
function queryDataFromMongo(query,dbopener,dbManager){
dbopener.collection('TESTTABLE').find(query).toArray(function(err, result){
if (err) {throw err};
console.log(result);
});
}
//更新数据
function updateDataFromMongo(query,update,dbopener,dbManager){
dbopener.collection('TESTTABLE').updateOne(query,update,function(err,res){
if (err) {throw err};
console.log(res.updatedCount);
});
}
//更新多条数据
function updateMoreDataFromMongo(query,update,dbopener,dbManager){
dbopener.collection('TESTTABLE').updateMany(query,update,function(err,res){
if (err) {throw err};
console.log(res.updatedCount);
});
}
//数据删除
function deleteOneData(query,dbopener,dbManager){
dbopener.collection('TESTTABLE').deleteOne(query,function(err,res){
if (err) {throw err};
console.log(res.updatedCount);
});
}
function deleteMoreData(query,dbopener,dbManager){
dbopener.collection('TESTTABLE').deleteMany(query,function(err,res){
if (err) {throw err};
console.log(res.updatedCount);
});
}
//查找时排序
function queryDataVisaSort(query,sortK,dbopener,dbManager){
dbopener.collection('TESTTABLE').find(query).sort(sortK).toArray(function(err,result){
if (err) { throw err};
console.log('sort'+JSON.stringify(result));
});
}
//分页查询
function queryPage(page,query,limit,dbopener,dbManager){
dbopener.collection('TESTTABLE').find(query).skip(page).limit(limit).toArray(function(err,result){
if (err) { throw err};
console.log('queryPage'+JSON.stringify(result));
});