在上篇中我们介绍了mongodb的安装和配置,下面我们介绍下NodeJs连接MongoDB,这里我们可以联想到我们使用Java的JDBC的处理,当时连接数据库时,需要对应数据库的驱动,这里也一样,需要我们下载NodeJS连接MongoDB的driver。
一、建立连接
var mongodb = require('mongodb');
var server = new mongodb.Server('localhost', 27017, {auto_reconnect: true});
var db = new mongodb.Db('mydb', server, {safe: true}); //数据库 mydb
db.open(function (err, db) {
if (!err) {
console.log('connect');
} else {
console.log(err);
}
});
如果最终显示connect则说明成功。
说明:
对mongodb的collection的操作有两种方法连接collection,分别为:
db.collection('mycoll',function(err,coll){});如果加上{strict:true},则会检查是否存在这个表,如果不存在,则报错。不加这个参数,函数不会在数据库上创建一个集合,直到你真正插入第一个文档。
db.createCollection('mycoll',function(err,coll){});如果加上{strict:true},则如果存在这个集合就会报错。不加这个参数,则如果存在,则忽略创建。
var mongodb = require('mongodb');
var server = new mongodb.Server('localhost', 27017, {auto_reconnect: true});
var db = new mongodb.Db('mydb', server, {safe: true});
db.open(function (err, db) {
if (!err) {
console.log('connect');
db.collection('mycoll', {strict: true}, function (err, collection) {//数据库中表名为 mycoll
if (err) {
console.log(err);
}
});
} else {
console.log(err);
}
});
注:这里的集合的概念和我们传统的数据库中的表的概念是类似的。
var mongodb = require('mongodb');
var server = new mongodb.Server('localhost', 27017, {auto_reconnect: true});
var db = new mongodb.Db('mydb', server, {safe: true});
db.open(function (err, db) {
if (!err) {
console.log('connect');
db.createCollection('mycoll', {strict: true}, function (err, collection) {
if (err) {
console.log(err);
}
});
} else {
console.log(err);
}
});
二、删除连接
var mongodb = require('mongodb');
var server = new mongodb.Server('localhost', 27017, {auto_reconnect: true});
var db = new mongodb.Db('mydb', server, {safe: true});
db.open(function (err, db) {
if (!err) {
console.log('connect');
db.dropCollection('mycoll', {strict: true}, function (err, result) {
console.log(result);
});
} else {
console.log(err);
}
});
三、CRUD
1、Insert操作
var mongodb = require('mongodb');
var server = new mongodb.Server('localhost', 27017, {auto_reconnect: true});
var db = new mongodb.Db('mydb', server, {safe: true});
db.open(function (err, db) {
if (!err) {
db.collection('mycoll', {strict: true}, function (err, collection) {
var tmp1 = {title: 'hello', number: 1};
collection.insert(tmp1, {safe: true}, function (err, result) {
console.log(result);
});
});
} else {
console.log(err);
}
});
2、Delete操作
var mongodb = require('mongodb');
var server = new mongodb.Server('localhost', 27017, {auto_reconnect: true});
var db = new mongodb.Db('mydb', server, {safe: true});
db.open(function (err, db) {
if (!err) {
db.collection('mycoll', {strict: true}, function (err, collection) {
collection.remove({title: 'hello'}, {safe: true}, function (err, result) {
console.log(result);
});
});
} else {
console.log(err);
}
});
3、Update操作
var mongodb = require('mongodb');
var server = new mongodb.Server('localhost', 27017, {auto_reconnect: true});
var db = new mongodb.Db('mydb', server, {safe: true});
db.open(function (err, db) {
if (!err) {
db.collection('mycoll', {strict: true}, function (err, collection) {
collection.update({title: 'hello'}, {$set: {number: 3}}, {safe: true}, function (err, result) {
console.log(result);
});
});
}
else {
console.log(err);
}
});
- $inc - increment a particular value by a certain amount
- $set - set a particular value
- $unset - delete a particular field (v1.3+)
- $push - append a value to an array
- $pushAll - append several values to an array
- $addToSet - adds value to the array only if its not in the array already
- $pop - removes the last element in an array
- $pull - remove a value(s) from an existing array
- $pullAll - remove several value(s) from an existing array
- $rename - renames the field
- $bit - bitwise operations
4、Select操作
var mongodb = require('mongodb');
var server = new mongodb.Server('localhost', 27017, {auto_reconnect: true});
var db = new mongodb.Db('mydb', server, {safe: true});
db.open(function (err, db) {
if (!err) {
db.collection('mycoll', {strict: true}, function (err, 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);
});
});
}
});
附:
MongoDB数据类型
-
Float is a 8 byte and is directly convertible to the Javascript type Number
-
Double class a special class representing a float value, this is especially useful when using capped collections where you need to ensure your values are always floats.
-
Integers is a bit trickier due to the fact that Javascript represents all Numbers as 64 bit floats meaning that the maximum integer value is at a 53 bit. Mongo has two types for integers, a 32 bit and a 64 bit. The driver will try to fit the value into 32 bits if it can and promote it to 64 bits if it has to. Similarly it will deserialize attempting to fit it into 53 bits if it can. If it cannot it will return an instance of Long to avoid loosing precession.
-
Long class a special class that let’s you store 64 bit integers and also let’s you operate on the 64 bits integers.
-
Date maps directly to a Javascript Date
-
RegExp maps directly to a Javascript RegExp
-
String maps directly to a Javascript String (encoded in utf8)
-
Binary class a special class that let’s you store data in Mongo DB
-
Code class a special class that let’s you store javascript functions in Mongo DB, can also provide a scope to run the method in
-
ObjectID class a special class that holds a MongoDB document identifier (the equivalent to a Primary key)
-
DbRef class a special class that let’s you include a reference in a document pointing to another object
-
Symbol class a special class that let’s you specify a symbol, not really relevant for javascript but for languages that supports the concept of symbols.
参考:http://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html
相关推荐
个人博客系统-VueJS-NodeJs-MongoDB包括前端(前台和后台),后端Express.zip
Angular-Angular-NodeJS-MongoDB-CustomersService.zip,与node.js restful services pluralsight课程集成angular的代码。与node.js restful services集成angular,Angularjs于2016年发布,是Angularjs的重写版。它...
reactjs-nodejs-expressjs-mongodb-assignment-master.rar
信息 使用nodejs作为后端服务器的Angular 2应用程序。 集成轻松部署到heroku并连接到mLab-mongodb...cd angular2-nodejs-mongodb # Install dependencies npm install # start server and client npm run start # sta
Vue+Element(html+css+js)+nodejs+MongoDB+mongose+axios+es6 数据工具: mongobooster+Postman axios的安装配置(已经全局安装),$是为了防止重复,调用的时候也都用axios import axios from 'axios' Vue.prototype.$...
使用Node.js和MongoDB开发高性能可伸缩微信公众平台应用。包含原理讲解和代码讲解,将近100页,非常优秀的教程。
官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装
官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装
官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装
官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装
官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装
官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装
nodejs + mongodb 资源 合集 01
api-nodejs-mongodb
App-NodeJS-Mongodb
uploadapp-nodejs-mongodb-images
simpleRestutant-Backend-nodejs-mongodb
reactjs-graphql-nodejs-mongodb
RestfulAPI-Nodejs-MongoDB
电子商务-nodejs-React-mongodb Sistema Ecommerce utilizando作为技术NodeJS,对mongodb做出React 安装Ferramentas:安装NodeJS 安装Mongodb 面食C:\ Program Files \ MongoDB \ Server \ 4.4 \ bin 环境变化...