安裝 mongoskin方法很簡單
在cmd中,進入nodejs目錄,輸入 npm install mongoskin回車即可安裝成功
獲取db
var mongoskin = require('mongoskin');
var str = 'mongodb://'
// + userName + ':' + password + '@'
+'127.0.0.1' +':' + 27017+ '/' + 'test';
var option = {
native_parser: true
};
var db= mongoskin.db(str, option);
其中的username和password @是有密碼的時候的參數,無密碼可以去掉
獲取表foo
var collection =db.collection('foo');
//查詢單個數據collection.findOne({'lo' :{'lat' : 73.0,'lon' : 72.0}},function(error,obj){
//回掉函數直接拿到了查找到的obj實體.
console.log('findOne');
console.log(obj);
});
//查詢多個數據collection.find({'username' : '999'},function(error,arrResult){
//回掉函數直接拿到了查找到的info實體.
console.log('find');
arrResult.forEach(function(item){
console.log(JSON.stringify(item));
});
});
//查詢username !="999"的數據 $ne代表不等於, $lt, $lte, $gt, $gte 分別代表 <, <=,>, >=,它們是用來設置查詢範圍collection.find({'username' : {$ne:'999'}},function(error,arrResult){
//回掉函數直接拿到了查找到的info實體.
console.log('find ne');
arrResult.forEach(function(item){
console.log(JSON.stringify(item));
});
});
//查詢username 在數組中的數據collection.find({'username':{$in:['2','3','4','5']}},function(error,result){
result.each(function(error,item){
console.log('==========>',item);
})
});
//查詢username 或查詢
collection.find({$or:[{'username':'aaa'},{age:'2'}]},function(error,result){
result.each(function(error,item){
console.log('==========>',item);
})
})
//添加數據var doc={'username':'123',age:2};
collection.insert(doc,function(error,result){
error?console.log('fail==========>',result):console.log('sucess==========>',result);
});
//更新數據(更新整個數據)
collection.update({'username':'999'},{'username':'999','sex':'nv',age:'7'},function(error,result){
console.log('========>',error,result);
});
//更新單個字段 $set更新字段 $unset 刪除字段
collection.update({'username':'999'},{$set:{'username':'666',age:'100'}},function(error,result){
console.log('=======>', error, result);
});
//更新單個字段 $push,$pushAll 添加字段,如果已經有該字段,添加字段
collection.findAndModify({'username':null},[],{$pushAll:{'newc':'haha naocan'}},{new:true,upset:true},function(error,result){
console.log('=======>', error, result);
});
//刪除字段collection.remove({'username':'123'},function(error){
console.log('=======>', error);
});