node.js操作mongodb简单示例分享
网络编程 2021-07-04 18:32www.168986.cn编程入门
MongoDB是基于Javascript语言的数据库,存储格式是JSON,而Node也是基于JavaScript的环境(库),所以node和mongoDB的搭配能减少因为数据转换带来的时间空间开销。今天我们来看看如何通过node.js来操作MongoliaDB
前两篇文章我们介绍了nodejs操作redis和MySQL,狼蚁网站SEO优化简要测试一下nodejs操作mongodb:
首先安装nodejs mongodb
npm install mongodb
代码
var mongodb = require('mongodb'); var server = new mongodb.Server('localhost', 27017, {auto_reconnect:true}); var db = new mongodb.Db('mydb', server, {safe:true}); //连接db db.open(function(err, db){ if(!err){ console.log('connect db'); // 连接Collection(可以认为是mysql的table) // 第1种连接方式 // db.collection('mycoll',{safe:true}, function(err, collection){ // if(err){ // console.log(err); // } // }); // 第2种连接方式 db.createCollection('mycoll', {safe:true}, function(err, collection){ if(err){ console.log(err); }else{ //新增数据 // var tmp1 = {id:'1',title:'hello',number:1}; // collection.insert(tmp1,{safe:true},function(err, result){ // console.log(result); // }); //更新数据 // collection.update({title:'hello'}, {$set:{number:3}}, {safe:true}, function(err, result){ // console.log(result); // }); // 删除数据 // collection.remove({title:'hello'},{safe:true},function(err,result){ // console.log(result); // }); // console.log(collection); // 查询数据 var tmp1 = {title:'hello'}; var tmp2 = {title:'world'}; collection.insert([tmp1,tmp2],{safe:true},function(err,result){ console.log(result); }); collection.find().toArray(function(err,docs){ console.log('find'); console.log(docs); }); collection.findOne(function(err,doc){ console.log('findOne'); console.log(doc); }); } }); // console.log('delete ...'); // //删除Collection // db.dropCollection('mycoll',{safe:true},function(err,result){ // if(err){ // console.log('err:'); // console.log(err); // }else{ // console.log('ok:'); // console.log(result); // } // }); }else{ console.log(err); } });
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程