Node.js 中的 MongoDB 基本操作

Node.js 中 MongoDB 数据库操作

起步

首先安装 Node.jsMongoDB

然后添加模块

1
npm install mongodb

示例

导入 MongoDB

1
var mongoClient = require('mongodb').MongoClient;

连接数据库

1
2
3
4
5
mongoClient.connect('mongodb://localhost:27017/myDatabase', function(err, db) {
...//在此进行增删查改
});

在进行增删查改操作前先要获取到collection

1
2
//在连接数据库的回调函数中输入
var collection = db.collection('myCollection');

添加数据

  • 插入单条数据

    1
    2
    3
    4
    5
    6
    collection.inserOne({'name':'shine'},function(err, result){
    if (!err){
    console.log(result);
    }
    db.close(); //操作完成,关闭数据库
    });
  • 插入多条数据
    多条数据采用数组形式添加到数据库中

    1
    2
    3
    4
    5
    6
    collection.inserMany([{'name':'shine'},{'age':23}],function(err, result){
    if (!err){
    console.log(result);
    }
    db.close(); //操作完成,关闭数据库
    });

更改数据

过滤得到数据,在{$set:{ 需要更改的数据 }}里改。

  • 更改一条数据
    更改过滤后得到的所有数据的第一条数据

    1
    2
    3
    4
    5
    6
    7
    8
    collection.updateOne({'name':'shine'},
    {$set:{'age':20}},
    function(err, result){
    if (!err){
    console.log(result);
    }
    db.close(); //操作完成,关闭数据库
    });
  • 更改所有数据
    将过滤到的多条数据全部更新

    1
    2
    3
    4
    5
    6
    7
    8
    collection.updateOne({'name':'shine'},
    {$set:{'age':20}},
    function(err, result){
    if (!err){
    console.log(result);
    }
    db.close(); //操作完成,关闭数据库
    });

删除数据

  • 删除单条数据
    删除过滤后所有数据中的第一条数据

    1
    2
    3
    4
    5
    6
    collection.deleteOne({'name':'shine'},function(err, result){
    if (!err){
    console.log(result);
    }
    db.close(); //操作完成,关闭数据库
    });
  • 删除所有数据
    删除过滤后所有数据

    1
    2
    3
    4
    5
    6
    collection.deleteMany({'name':'shine'},function(err, result){
    if (!err){
    console.log(result);
    }
    db.close(); //操作完成,关闭数据库
    });

查询数据

查找数据需要将数据转换成(toArray())数组

  • 查找collection下的所有数据

    1
    2
    3
    4
    5
    6
    colleciotn.find({}).toArray(function(err, result) {
    if (!err){
    console.log(result);
    }
    db.close(); //操作完成,关闭数据库
    });
  • 查找含有指定数据的所有数据

    1
    2
    3
    4
    5
    6
    colleciotn.find({'name':'shine'}).toArray(function(err, result) {
    if (!err){
    console.log(result);
    }
    db.close(); //操作完成,关闭数据库
    });

使用 mongoose 来操作数据库

起步

添加 mongoose 模块

1
npm install mongoose

导入模块

1
var mongoose = require('mongoose');

连接数据库

1
mongoose.connect('mongodb://localhost:27017/myDatabase')

示例

mongoose 名词解释

  • Schema : 一种以文件形式存储的数据库模型骨架,不具备数据库的操作能力

  • Model : 由Schema发布生成的模型,具有抽象属性和行为的数据库操作对

  • Entity : 由Model创建的实体,他的操作也会影响数据库

Schema 生成 Model,Model 创造 Entity,Model 和 Entity 都可对数据库操作造成影响,但 Model 比 Entity 更具操作性。

定义 Model

声明自定义的名称

1
2
3
var mySchema; //文本属性
var myModel; //数据库模型
var myEntity; //实体

生成 Schema

1
2
3
4
5
mySchema = new Schema({
name : String,
age : number,
date : Date
});

访问 Model

1
myModel = db.model('ModelName', mySchema, 'collectionName');

创建 Entity

1
2
3
4
5
myEntity = new myModel({
name : 'shine',
age : 23,
date : Date.now
});

增删改查

增加数据

  • 方式一:通过 entity 来添加
    创建完实体之后直接通过 save() 来保存数据

    1
    myEntity.save();
  • 方式二:通过 model 来添加
    该方法可以不需要创建实体

    1
    2
    3
    4
    5
    myModel.create({
    name : 'shine',
    age : 23,
    date : Date.now
    });

    多条数据可以在数组中添加json数据

删除数据

Model 和 Entity 都是用 remove() 方法来删除数据

  • 删除一条数据
    通过查询找到相应的数据中的第一条数据并删除

    1
    2
    3
    4
    5
    6
    myModel.findOne({'name':'shine'}, function(err, doc){
    doc.remove(); //doc就是指找到的那条数据
    });
    myModel.findById('3asd87a9872892379a', function(err, doc){
    doc.remove(); //doc就是指找到的那条数据
    });
  • 删除所有数据
    找到含有相应数据的所有数据全部删除

    1
    2
    //删除所有含有{'name':'shine'}的数据
    myModel.remove({'name':'shine'});

更新数据

  • 更新单条数据

    • 方式一:直接找到单条数据通过save更新

      1
      2
      3
      4
      myModel.findById('3asd87a9872892379a', function(err, doc){
      doc.age = 20;
      doc.save(); //doc对象属于Entity,也能使用save方法
      });
    • 方式二:通过Model使用update更新

      1
      myModel.update({'name':'shine'}, {$set:{'age':20}});
  • 更新多条数据
    通过添加{multi : true}来设置找到的多条数据

    1
    myModel.update({'name':'shine'}, {$set:{'age':20}}, {multi : true});

查找数据

  • 直接搜索查询
    其中第二个参数是为了过滤查询到的结果

    1
    myModel.find({'name':'shine'}, _id);
  • 条件查询(链式搜索)
    通过添加搜索条件来将结果进行过滤

    1
    2
    3
    4
    5
    6
    7
    8
    myModel.find({'name':'shine'})
    .where('age').gt(10)
    .limit(10)
    .sort('-age')
    .select('name')
    .exec(function(err, res){
    console.log(res);
    }); //只要在执行exec方法时才执行查询,而且必须有回调函数

    详细 API 可以通过 Aggregation Pipeline Operators 查询