NodeJS中MongoDB驱动mongodb使用简介

转自于:http://www.open-open.com/lib/view/open1447489698991.html

虽然说在NodeJS下连接MongoDB用Mongoose的较多,但作为其基础的mongodb库了解一下还是很有必要的。

mongodb库在npmjs的主页: mongodb

安装

一如既往的通过npm安装,命令npm install mongodb

连接数据库

通过MongoClient.connect连接数据库,在回调中会返回db对象以供之后使用。

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/dbname';
MongoClient.connect(url, function(err, db) {
	if(err){
		console.error(err);
		return;
	}else{
		console.log("Connected correctly to server");
		db.close();
	}
});

获得Collection

调用db对象的collection获得collection

var collection = db.collection('collectionName');

添加记录

调用collection的insert|insertMany方法添加记录。

collection.insert[|insertMangy]({name:"myName",age:"myAge"},function(err,result){
	if(err){
		console.error(err);
	}else{
		console.log("insert result:");
		console.log(result);
	}
})

更新记录

调用collection的updateOne方法更新单个记录。

collection.updateOne({ a : 2 }, { $set: { b : 1 } }, function(err, result) {
	if(err){
		console.error(err);
	}else{
		console.log("update result:");
		console.log(result);
	}
});

删除记录

调用collection的deleteOne方法更新单个记录。

collection.deleteOne({ a : 3 }, function(err, result) {
    if(err){
        console.error(err);
    }else{
        console.log("delete result:");
        console.log(result);
    }
  });

查询记录

调用collection的find方法查找记录,find方法的参数为查找条件。

collection.find({}).toArray(function(err, docs) {
    if(err){
        console.error(err);
    }else{
        console.log("find result:");
        console.log(result);
    }
  });

仅仅写了基础的CRUD,详情参考 http://mongodb.github.io/node-mongodb-native/2.0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值