MongoDB关键点集锦(更新中...)

来源:互联网 发布:ubuntu登陆界面修改 编辑:程序博客网 时间:2024/04/30 10:59

0、 mongodb的使用方法

var mongodbClient = require('./db'); //mongodb是一个数据库实例。var url = "mongodb://"+ setting.host +":"+ setting.port +"/" + setting.db;// 要存入数据库的用户信息文档或其他数据模型function User(user) {  this.name = user.name;  this.password = user.password;  this.email = user.email;}/* 定义方法 */// 保存用户User.prototype.save = function(callback) {  var user = {   name: this.name,   password: this.password,   email: this.email,   head: head  };  mongodbClient.connect(url, function(err, db) {    var collection = db.collection('users');    collection.insertOne(user, function(err,result) {      if(err) {        return callback(err);      }       callback(null, result);      db.close();    })} /* 这一段如果使用async,可以 async.waterfall([   function(cb) {     mongodbClient.connect(url, function(err, db) {       cb(err, db);     });   },   function(db, cb) {     var collection = db.collection('users');     collection.insertOne(user, function(err, result) {       cb(err, db, result);     });   } ], function(err, db, result) {   if(err) {     return callback(err);   }   callback(null, result);   db.close(); }) 这样使流程更加清晰。避免了回调嵌套。 */// 经过打印后,这里的result形式如下:所以要获得user对象,需要使用result.ops[0]。使用mongoose就不会有这个问题。/*{ result: { ok: 1, n: 1 },  ops:   [ { name: 'vbb',       password: '4bca24304861acde5770fdbe3cc2503b',       email: 'd@qq.com',       head: 'http://www.gravatar.com/avatar/3ae9604a6b55549de041ec6d13612609?s=48',       _id: 58817e28cdb7e21e5894c179 } ],  insertedCount: 1,  insertedIds: [ 58817e28cdb7e21e5894c179 ] }*///etc.

1、MongoError: server instance in invalid state undefined

参考segmentfault的一个解答

看起来你用的是node-mongodb-native驱动。老版本确实有使用过DB作为顶级对象,不过现在的驱动通常建议把MongoClient用为顶级对象使用。直接参考驱动文档:
https://github.com/mongodb/node-mongodb-native#connecting-to-mongodb
注意MongoClient维护着连接池,所以通常当你的应用退出前都可以不要关闭,保留一个单例的MongoClient一直用就可以了。

我按照这个建议后,确实修复了这个问题。修改后的代码如下(关键代码):

// 使用mongoClient作为顶级对象,而不是require('mongodb')var mongodbClient = require('mongodb').MongoClient;// 连接数据库取代了db.open(...)mongodbClient.connect(url, function(err, db) {    if(err) {      return callback(err);    }    var collection = db.collection('posts');    collection.insertOne(post, function(err) {      if(err) {        return callback(err);      }       callback(null);      db.close();    })  })

通过collection操作数据库的方法。我打印了collection.__proto__,如下所示:

{ collectionName: [Getter],  namespace: [Getter],  readConcern: [Getter],  writeConcern: [Getter],  hint: [Getter/Setter],  find: [Function],  insertOne: [Function],  insertMany: [Function],  bulkWrite: [Function],  insert: [Function],  updateOne: [Function],  replaceOne: [Function],  updateMany: [Function],  update: [Function],  deleteOne: [Function],  removeOne: [Function],  deleteMany: [Function],  removeMany: [Function],  remove: [Function],  save: [Function],  findOne: [Function],  rename: [Function],  drop: [Function],  options: [Function],  isCapped: [Function],  createIndex: [Function],  createIndexes: [Function],  dropIndex: [Function],  dropIndexes: [Function],  dropAllIndexes: [Function],  reIndex: [Function],  listIndexes: [Function],  ensureIndex: [Function],  indexExists: [Function],  indexInformation: [Function],  count: [Function],  distinct: [Function],  indexes: [Function],  stats: [Function],  findOneAndDelete: [Function],  findOneAndReplace: [Function],  findOneAndUpdate: [Function],  findAndModify: [Function],  findAndRemove: [Function],  aggregate: [Function],  parallelCollectionScan: [Function],  geoNear: [Function],  geoHaystackSearch: [Function],  group: [Function],  mapReduce: [Function],  initializeUnorderedBulkOp: [Function],  initializeOrderedBulkOp: [Function] }

2、mongodb更新一个数组,如commets是一个数组,添加comment

collection.update({  "name": name,}, {  $push: {"comments": comment}})

3、distinct(key, query, options, callback){Promise}

查询集合返回一个带有key键的值组成的列表,列表的值是不重复的。其中每个集合需要满足query条件。

var MongoClient = require('mongodb').MongoClient,    test = require('assert');MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {  // 创建集合  var collection = db.collection('distinctExample2');  // 插入多个文档  collection.insertMany([{a:0, b:{c:'a'}}, {a:1, b:{c:'b'}}, {a:1, b:{c:'c'}},    {a:2, b:{c:'a'}}, {a:3}, {a:3}, {a:5, c:1}], {w:1}, function(err, ids) {    // 返回含有c是1的集合的a属性的值组成的列表。 [5]    collection.distinct('a', {c:1}, function(err, docs) {      test.deepEqual([5], docs.sort());      db.close();    });  })});

4、查询所有tags中包含tag的文档。tags是数组 [‘a’, ‘b’, ‘c’]的形式

collection.find({tags: 'a'}) // 这样也可以查询到这个集合

5、使用$inc增加某个字段

// 查询到这个文档,将`pv`字段加1,如果不存在`pv`字段,则创建pv字段,初始值为0,并加1collection.updateOne({  "name": name,  "time.day": day,  "title": title}, {  $inc: {"pv": 1}}, function(err) {  if(err) {    return callback(err);  }  db.close();})

6、mongodb分页,主要用到countskiplimit属性

Post.getTen = function(name, page, callback) {  mongodbClient.connect(url, function(err, db) {    if(err) {      return callback(err)    }    var collection = db.collection('posts');    var query = {};    if(name) {      query.name = name;    }    // 对于一个query对象,首先使用`count()`来查询到总数目,结果值赋给参数`total`,比如`total`是93,然后使用`find()`查询,并跳过(page-1)*10个结果,返回之后的10个结果,按时间(`time`)降序排序。1是升序,也是默认的。-1是降序    collection.count(query, function(err, total) {      collection.find(query).skip((page - 1) * 10).limit(10).sort({        time: -1      }).toArray(function(err, docs) {        if(err) {          return callback(err);        }        callback(null, docs, total);        db.close();      })    })  })}
0 0