http://www.sufeinet.com/plugin.php?id=keke_group

苏飞论坛

 找回密码
 马上注册

QQ登录

只需一步,快速开始

分布式系统框架(V2.0) 轻松承载百亿数据,千万流量!讨论专区 - 源码下载 - 官方教程

HttpHelper爬虫框架(V2.7-含.netcore) HttpHelper官方出品,爬虫框架讨论区 - 源码下载 - 在线测试和代码生成

HttpHelper爬虫类(V2.0) 开源的爬虫类,支持多种模式和属性 源码 - 代码生成器 - 讨论区 - 教程- 例子

查看: 5879|回复: 5

[node.js] node.js连接Mongodb的例子

[复制链接]
发表于 2014-3-7 11:03:37 | 显示全部楼层 |阅读模式
首先要安装驱动插件
直接在Nodejs的主目录执行如下命令就行了
  1. npm install mongodb
复制代码
等安装好之后如下
QQ截图20140307110133.jpg
现在就可以写代码了,
Server端代码测试如下
[JavaScript] 纯文本查看 复制代码
var MongoClient = require('mongodb').MongoClient
    , format = require('util').format;

  MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
    if(err) throw err;

    var collection = db.collection('test_insert');
    collection.insert({a:2}, function(err, docs) {

      collection.count(function(err, count) {
        console.log(format("count = %s", count));
      });

      // Locate all the entries using find
      collection.find().toArray(function(err, results) {
        console.dir(results);
        // Let's close the db
        db.close();
      });
    });
  })

写法就是这样,再看一个例子
[JavaScript] 纯文本查看 复制代码
var mongodb = require('mongodb');

var server = new mongodb.Server("192.168.1.16", 27017, {}); //本地27017端口

new mongodb.Db('test', server, {}).open(function (error, client) {//数据库:test
//    if (error) throw error;
    var collection = new mongodb.Collection(client, 'Messages'); //表:Messages
    collection.find(function (error, cursor) {
        cursor.each(function (error, doc) {
            if (doc) {
                console.log("MyName:" + doc.MyName + " msg:" + doc.msg);
            }
        });
    });
});

好了接下来大家自己研究吧。



1. 开通SVIP会员,免费下载本站所有源码,不限次数据,不限时间
2. 加官方QQ群,加官方微信群获取更多资源和帮助
3. 找站长苏飞做网站、商城、CRM、小程序、App、爬虫相关、项目外包等点这里
 楼主| 发表于 2014-3-7 11:07:00 | 显示全部楼层
Documentation

If this document doesn't answer your questions, see the source of Collection or Cursor, or the documentation at MongoDB for query and update formats.

Find

The find method is actually a factory method to create Cursor objects. A Cursor lazily uses the connection the first time you call nextObject, each, or toArray.

The basic operation on a cursor is the nextObject method that fetches the next matching document from the database. The convenience methods each and toArray call nextObject until the cursor is exhausted.

Signatures:

[JavaScript] 纯文本查看 复制代码
  var cursor = collection.find(query, [fields], options);
  cursor.sort(fields).limit(n).skip(m).

  cursor.nextObject(function(err, doc) {});
  cursor.each(function(err, doc) {});
  cursor.toArray(function(err, docs) {});

  cursor.rewind()  // reset the cursor to its initial state.

Useful chainable methods of cursor. These can optionally be options of find instead of method calls:

[C#] 纯文本查看 复制代码
.limit(n).skip(m) to control paging.
.sort(fields) Order by the given fields. There are several equivalent syntaxes:
.sort({field1: -1, field2: 1}) descending by field1, then ascending by field2.
.sort([['field1', 'desc'], ['field2', 'asc']]) same as above
.sort([['field1', 'desc'], 'field2']) same as above
.sort('field1') ascending by field1

Other options of find:

[C#] 纯文本查看 复制代码
fields the fields to fetch (to avoid transferring the entire document)
tailable if true, makes the cursor tailable.
batchSize The number of the subset of results to request the database to return for every request. This should initially be greater than 1 otherwise the database will automatically close the cursor. The batch size can be set to 1 with batchSize(n, function(err){}) after performing the initial query to the database.
hint See Optimization: hint.
explain turns this into an explain query. You can also call explain() on any cursor to fetch the explanation.
snapshot prevents documents that are updated while the query is active from being returned multiple times. See more details about query snapshots.
timeout if false, asks MongoDb not to time out this cursor after an inactivity period.

For information on how to create queries, see the MongoDB section on querying.

[JavaScript] 纯文本查看 复制代码
  var MongoClient = require('mongodb').MongoClient
    , format = require('util').format;    

  MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
    if(err) throw err;

    var collection = db
      .collection('test')
      .find({})
      .limit(10)
      .toArray(function(err, docs) {
        console.dir(docs);
    });
  });

Insert

Signature:

[JavaScript] 纯文本查看 复制代码
collection.insert(docs, options, [callback]);

where docs can be a single document or an array of documents.

Useful options:

[C#] 纯文本查看 复制代码
safe:true Should always set if you have a callback.

See also: MongoDB docs for insert.

[JavaScript] 纯文本查看 复制代码
var MongoClient = require('mongodb').MongoClient
    , format = require('util').format;    

  MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
    if(err) throw err;

    db.collection('test').insert({hello: 'world'}, {w:1}, function(err, objects) {
      if (err) console.warn(err.message);
      if (err && err.message.indexOf('E11000 ') !== -1) {
        // this _id was already inserted in the database
      }
    });
  });

Note that there's no reason to pass a callback to the insert or update commands unless you use the safe:true option. If you don't specify safe:true, then your callback will be called immediately.

Update: update and insert (upsert)

The update operation will update the first document that matches your query (or all documents that match if you use multi:true). If safe:true, upsert is not set, and no documents match, your callback will return 0 documents updated.

See the MongoDB docs for the modifier ($inc, $set, $push, etc.) formats.

Signature:

[JavaScript] 纯文本查看 复制代码
collection.update(criteria, objNew, options, [callback]);

Useful options:

[C#] 纯文本查看 复制代码
safe:true Should always set if you have a callback.
multi:true If set, all matching documents are updated, not just the first.
upsert:true Atomically inserts the document if no documents matched.

Example for update:

[JavaScript] 纯文本查看 复制代码
var MongoClient = require('mongodb').MongoClient
    , format = require('util').format;    

  MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
    if(err) throw err;

    db.collection('test').update({hi: 'here'}, {$set: {hi: 'there'}}, {w:1}, function(err) {
      if (err) console.warn(err.message);
      else console.log('successfully updated');
    });
  });

Find and modify

findAndModify is like update, but it also gives the updated document to your callback. But there are a few key differences between findAndModify and update:

  • The signatures differ.
  • You can only findAndModify a single item, not multiple items.

Signature:

[JavaScript] 纯文本查看 复制代码
collection.findAndModify(query, sort, update, options, callback)

The sort parameter is used to specify which object to operate on, if more than one document matches. It takes the same format as the cursor sort (see Connection.find above).

See the MongoDB docs for findAndModify for more details.

Useful options:

[C#] 纯文本查看 复制代码
remove:true set to a true to remove the object before returning
new:true set to true if you want to return the modified object rather than the original. Ignored for remove.
upsert:true Atomically inserts the document if no documents matched.

Example for findAndModify:

[JavaScript] 纯文本查看 复制代码
 var MongoClient = require('mongodb').MongoClient
    , format = require('util').format;    

  MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
    if(err) throw err;
    db.collection('test').findAndModify({hello: 'world'}, [['_id','asc']], {$set: {hi: 'there'}}, {}, function(err, object) {
      if (err) console.warn(err.message);
      else console.dir(object);  // undefined if no matching object exists.
    });
  });


 楼主| 发表于 2014-3-7 14:25:20 | 显示全部楼层
添加账户密码的方法
[C#] 纯文本查看 复制代码
var constr = "mongodb://sa:123456@192.168.1.16:27017";
发表于 2014-6-28 23:55:28 | 显示全部楼层
还是不是太明白哦。那个要Server端写的代码要在哪个文件下创建啊。最近在弄node连接mongodb老是出错。
 楼主| 发表于 2014-9-4 23:20:47 | 显示全部楼层
包田耘 发表于 2014-6-28 23:55
还是不是太明白哦。那个要Server端写的代码要在哪个文件下创建啊。最近在弄node连接mongodb老是出错。

才看到,放哪里都行,运行时写上路径就行了
 楼主| 发表于 2014-9-4 23:20:49 | 显示全部楼层
包田耘 发表于 2014-6-28 23:55
还是不是太明白哦。那个要Server端写的代码要在哪个文件下创建啊。最近在弄node连接mongodb老是出错。

才看到,放哪里都行,运行时写上路径就行了
您需要登录后才可以回帖 登录 | 马上注册

本版积分规则

QQ|手机版|小黑屋|手机版|联系我们|关于我们|广告合作|苏飞论坛 ( 豫ICP备18043678号-2)

GMT+8, 2024-5-1 19:17

© 2014-2021

快速回复 返回顶部 返回列表