`

02-Nodejs与mongodb

阅读更多
在上篇中我们介绍了mongodb的安装和配置,下面我们介绍下NodeJs连接MongoDB,这里我们可以联想到我们使用JavaJDBC的处理,当时连接数据库时,需要对应数据库的驱动,这里也一样,需要我们下载NodeJS连接MongoDBdriver

 

 

一、建立连接

 

    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则说明成功。

 

说明:

mongodbcollection的操作有两种方法连接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

 

 

 

 

  • 大小: 79.6 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics