首先要安装mongodb,具体安装过程参考菜鸟教程html
由于我是mac,因此如下内容以OS系统为主,Windows系统建议参考 菜鸟教程
进入mongodb的bin文件目录下,运行mongod执行文件node
sudo ./mongod //以管理员身份运行
而后另开一个命令行,一样进入mongodb的bin文件目录下,运行mongo执行文件,而后便会进入mongodb的shell环境mongodb
./mongo //进入mongodb的shell环境 >2+2 4
在mongodb的shell环境中能够直接操做数据库,语法请参考菜鸟教程
但shell操做比较反人类,我在这里推荐mongodb的GUI软件——Robo 3T,能够自行在官网下载shell
在nodejs环境中我选择的是mongoose
模块数据库
var mongoose=require('mongoose')
详情请戳 mongoose官网
链接数据库数组
mongoose.connect('mongodb://localhost:27017/test')//test即为存储的数据库名称,若是不存在将会自动生成
var CatSchema=mongoose.Schema({ name:String, age:Number }) var Cat=mongoose.model('Cat',CatSchema) //也能够合二为一,直接定义model var Cat=mongoose.model('Cat',{ name:String, age:Number }) //mongoose.model的第一个参数的字符串加上字母s即是储存在的数据库表单的名称(Cats)
mongoose Schema经常使用预置类型:
var kitty=new Cat({ name:'Kitty', age:3 })
kitty.save(function(err,res){ if(err) console.error(err) else console.log(res)//res为保存成功的对象 })
var where={ name:'Kitty' } var update={ age:4 } Cat.update(where,update,function(err,res){ if(err) console.error(err) else console.log(res) })
经过ID查找并更新的方法mongoose
Cat.findByIdAndUpdate(whereById,update,function(err,res)){ if(err) console.error(err) else console.log(res) })
Cat.remove(where,function(err,res)) //经过ID查找并删除 Cat.findByIdAndRomove(where,function(err,res))
Cat.find(where,function(err,res))//res 返回查找到的对象数组 //能够限定输出的内容 var opt={ name:1//选择输出的值为1,不输出的值为0(其余不指定默认为0) } Cat.find(where,opt,function(err,res)) //var where=_id Cat.findById(where,function(err,res))//res 输出查询到的对象
Cat.count(where,function(err,res))//res输出查询数量