连接启动你的mongodb服务首先确保你已经安装了mongodb并配置了mongodb环境变量。在任意目录(推荐在非中文目录下)新建数据库文件夹,并在该文件夹下新建测试文件夹(确保该文件夹为空)。然后打开cmd输入:mongod--dbpath'测试文件夹的绝对路径——E:\database\test'waitingforconnectionsonport27017表示你已经在localhost:27017端口开启了服务。这时候再次进入test文件夹,里面会有很多WT文件。创建连接,新建index.js(任意目录,最好新建一个mongodbDemo文件夹,方便管理)。varmongoose=require('mongoose');mongoose.connect('mongodb://localhost/test');vardb=mongoose.connection;db.on('error',console.error.bind(控制台,'mongodb连接错误:'));db.once('open',function(){console.log('mongodb连接成功!');});安装mongoose依赖包,运行这个文件npminstallmongoosenodeindex.js说明连接数据库成功。写入第一个数据createmongoose写入数据有两种方式,分别是Model.create()和Documents.save()【也就是上面的Entity】;1、写入数据前,新建一个modelvarCatSchema=newmongoose.Schema({//新建一个modelobjectname:String});varCatModel=mongoose.model('Cat',CatSchema);//这一步正式写入数据库,数据库对应的model命名为Cat2.插入一条数据//Model.createCatModel.create({name:'ketty'},function(err,res){//第一个参数指定为错误信息console.log(err);console.log(res);})//promise写CatModel.create({name:'kitty'}).then(res=>{console.log(res)})//成功返回当前data.catch(err=>{console.log(err)});//Documents.save()varcatDoc=newCatModel({name:'ketty'});catDoc.save(function(err,res){if(err)console.log(err);console.log(res);});基于模型的查询简单查询Model.find().then(res=>{//传空匹配所有log(res);}).catch(err=>{log(err);});Model.find({name:'kitty'}).then(res=>{//匹配所有名字为kitty的数据log(res);//如果查询数据res为[]}).catch(err=>{log(err);});Model.findOne({name:'kitty'}).then(res=>{//匹配第一个名字为kitty的数据log(资源);//如果查询数据res为null}).catch(err=>{log(err);});Model.findById(id).then(res=>{//根据id查询//tido}).catch(err=>{//tido})find和findOne只接受Object作为参数,如果没有传递参数,则默认为{}传递其他数据类型会抛出异常条件query"$lt"小于"$lte"小于等于"$gt"大于"$gte"大于等于"$ne"不等于//查询年龄更大小于或等于18且小于或等于30DocumentModel.find({'age':{'$get':18,'$lte':30}});orquery'$in'一键对应多个值'$nin'同上,一个键不对应指定值"$or"多个条件匹配,$in可以嵌套使用"$not"相同如上反转,查询不匹配特定模式的文档//queryageequals20or21or21or'haha'DocumentModel.find({'age':{'$in':[20,21,22.'哈哈']}});//查询年龄等于18或名字等于'学友'的文档Model.find({'$or':[{'age':18},{'name':'学友'}]});类型查询“$exists”是否存在可以匹配自身和不存在值的属性null,想要匹配key的值为null,则需要使用“$exists”条件判断keyalreadyexists//查询age值为null的文档Model.find('age':{'$in':[null],'exists':true});//查询所有name属性为null的文档Model.find({name:{$exists:true}});//查询所有没有电话属性的文档Model.find({telephone:{$exists:false}});正则表达式MongoDb使用兼容Prel的正则表达式库来匹配正则表达式//查询名称为joe的文档,忽略大小写Model.find({'name':/joe/i})//查询匹配各种大小写组合Model.find({'name':/joe?/i})queryarray'$all'匹配数组中的多个元素'$size'匹配数组长度'$slice'querysubCollectionreturn//queryfordocumentswith10在数组(数组类型)的键中,array:[1,2,3,4,5,10]将匹配到Model.find({'array':10});//查询array(数组类型)key中下标5对应的值为10,array:[1,2,3,4,5,10]会匹配到Model.find({'array[5]':10});//查询匹配数组中同时有5和10的文档Model.find({'array':[5,10]});//查询匹配长度thearray数组3的文档Model.find({'array':{'$size':3}});//查询匹配数组的前10个元素Model.find({'array':{'$skice':10}});//查询第5到第10个元素的匹配数组Model.find({'array':{'$skice':[5,10]}});where_javacript语句查询可以用$where执行任何javacript语句作为查询的一部分,如果回调函数返回true,则文档作为结果的一部分返回Model.find({"$where":function(){if(this.x!==null&&this.y!==null){returnthis.x+this.y===10?true:false;//return将替换returnresult}else{returntrue;}}})Model.find({"$where":"this.x+this.y===10"})//this指向ModelModel.find({"$where":"function(){returnthis.x+this.y===10;}"})表查询实现联表查询,需要将连接的Model的主键_id指向一个需要与Model对应的属性使用populate查询如下://*****************CreateModel************varcityModel=mongoose.model('city',{cityName:String,townList:[]});varcountryModel=mongoose.model('country',{country:String,cityList:[{type:mongoose.Schema.ObjectId,ref:'city'//将'sity'Model的主键对应国家的cityList}]});//*****************插入数据****************************cityModel.create({cityName:'上海',townList:['陆家嘴']});cityModel.create({cityName:'广州',townList:['天河']});cityModel.create({cityName:'北京',townList:['赵阳']});varcountryObj={country:'中国',cityList:[]}cityModel.find().then(res=>{//查出所有数据,将对应的_id存入数组for(letiinres){countryObj.cityList.push(res[i]._id);}//插入国家数据countryModel.create(countryObj,function(err,res){console.log(err);console.log('res'+res);});});//*****************查询结果*********************countryModel.find().then(res=>{//普通通查询console.log(res);}).catch(err=>{console.log(err);})/*结果为[{cityList:[5a4ded2b78110500d8b94726,5a4ded2b78110500d8b94725,5a4ded2b78110500d8b94727],_id:5a4df149c249713348a2f546,country:'china',__v:0}]*/countryModel.find({country:'china'}).populate('cityList').then(res=>{//填充查询console.log(res);})/*[{cityList:[[Object],[Object],[Object]],_id:5a4df149c249713348a2f546,country:'china',__v:0}]*/cursorlimit(3)限制返回结果数量skip(3)跳过前3个文档,返回剩下的sort('username':1,'age':-1})sortkey对应文档的key名称,value代表排序方向,1升序,-1降序更新数据'$inc'增减修饰符,只对数字有效。下面的例子:找到age=22的文档,修改文档的age值增加1Model.update({'age':22},{'$inc':{'age':1}});'$set'指定键的值。如果密钥不存在,请创建它。它可以是任何支持的类型MondoDB.Model.update({'age':22},{'$set':{'age':'haha'}});'$unset'deleteakeyModel.update({'age':22},{'$unset':{'age':'haha'}});Arrayupdate'$push'将一个数组成员推送到一个key,如果key不存在,则创建Model.update({'age':22},{'$push':{'array':10}});'$一个ddToSet'向数组中添加一个元素,存在则不添加Model.update({'age':22},{'$addToSet':{'array':10}});'$each'遍历数组,$push修饰符可以插入多个值Model.update({'age':22},{'$push':{'array':{'$each':[1,2,3,4,5]}}});'$pop'从数组末尾删除一个元素Model.update({'age':22},{'$pop':{'array':1}});'$pull'到数组删除Model中的指定元素.update({'age':22},{'$pull':{'array':10}});删除Model.remove(条件,回调);//conditions是查询条件,可以参考find
