要安装mongodb,首先要安装mongodb。具体安装过程参考菜鸟教程运行mongodb。因为我是mac,下面的内容都是基于OS系统的。Windows系统,建议参考菜鸟教程,进入mongodb的bin文件目录,运行mongod执行文件sudo./mongod//以管理员身份运行,再打开一个命令行,同样进入mongodb的bin文件目录mongodb,运行mongo执行文件,然后进入mongodb的shell环境/mongo//进入mongodb的shell环境>2+24在mongodb的shell环境下,可以直接操作数据库。语法可以参考菜鸟教程,但是shell操作比较反人类。这里推荐mongodb的GUI软件——Robo3T。nodejs环境下自行从官网下载nodejs中mongodb的API我选择的是mongoose模块varmongoose=require('mongoose')mongoose语法详解请点击mongoose官网连接数据库mongoose.connect('mongodb://localhost:27017/test')//test为存储的数据库名,如果不存在则自动生成并定义Schema和模型varCatSchema=mongoose.Schema({name:String,age:Number})varCat=mongoose.model('Cat',CatSchema)//也可以合二为一,直接定义modelvarCat=mongoose.model('Cat',{name:String,age:Number})//mongoose.model第一个参数的字符串加上字母s就是存储在(Cats)MongooseSchema中的数据库形式的名称常用预设类型:StringStringNumberNumberDateDateBoolean布尔值和数组组合:[String][Number]...创建实例varkitty=newCat({name:'Kitty',age:3})insertkitty.save(function(err,res){if(err)console.error(err)elseCconsole.log(res)//res为保存成功的对象})updatevarwhere={name:'Kitty'}varupdate={age:4}Cat.update(where,update,function(err,res){if(err)console.error(err)elseconsole.log(res)})通过ID查找和更新的方法Cat.findByIdAndUpdate(whereById,update,function(err,res)){if(err)console.error(err)elseconsole.log(res)})removeCat.remove(where,function(err,res))//通过ID查找并移除Cat.findByIdAndRomove(where,function(err,res))findCat.find(where,function(err,res))//res返回找到的对象数组//可以限制输出内容varopt={name:1//选择输出值为1,非输出值为0(其他的不是指定默认为0)}Cat.find(where,opt,function(err,res))//varwhere=_idCat.findById(where,function(err,res))//res输出查询到的对象查询猫。count(where,function(err,res))//res输出查询数量
