node js 使用mongoskin 操作mongodb



安装 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);
});








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章