MongoDB数据库存储模型

简介

MongoDB是一个开源的NoSQL数据库管理系统,它使用文档存储模型来存储数据。与传统的关系型数据库不同,MongoDB不使用表格,而是使用集合(Collections)来存储数据。它以灵活的文档(Documents)形式来表示数据,每个文档可以有不同的结构。

文档存储模型

MongoDB使用文档存储模型来存储数据,一个文档可以看作是一个键值对集合,其中键是字符串,值可以是各种类型,比如字符串、整数、浮点数、数组、日期等等。文档中的键是唯一的,用于标识文档中的值。

MongoDB的文档可以嵌套,也就是说一个文档中可以包含其他文档,这样可以更好地组织和表示数据。嵌套文档的结构可以是任意的,没有固定的模式,这使得MongoDB非常灵活。

集合

在MongoDB中,数据存储在集合(Collections)中。一个集合可以看作是一个表格,但是与关系型数据库中的表格不同,集合中的文档可以有不同的结构。集合是动态的,即可以在插入文档时创建集合,不需要预先定义。

文档操作

插入文档

使用insertOneinsertMany方法可以向集合中插入文档。insertOne方法用于插入单个文档,insertMany方法用于插入多个文档。

示例代码:

// 连接到MongoDB数据库
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/mydb';

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log('数据库已连接');
  
  // 插入单个文档
  const document = { name: 'John', age: 30 };
  db.collection('customers').insertOne(document, function(err, res) {
    if (err) throw err;
    console.log('文档已插入');
    db.close();
  });

  // 插入多个文档
  const documents = [
    { name: 'Peter', age: 25 },
    { name: 'Amy', age: 28 },
    { name: 'David', age: 35 }
  ];
  db.collection('customers').insertMany(documents, function(err, res) {
    if (err) throw err;
    console.log('文档已插入');
    db.close();
  });
});

查询文档

使用find方法可以查询集合中的文档。可以使用各种查询条件来过滤文档的结果,比如指定键值对、范围查询、正则表达式等等。

示例代码:

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log('数据库已连接');
  
  // 查询所有文档
  db.collection('customers').find({}).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });

  // 查询指定条件的文档
  db.collection('customers').find({ age: { $gt: 30 } }).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });
});

更新文档

使用updateOneupdateMany方法可以更新集合中的文档。可以使用不同的操作符来进行更新,比如$set$inc$unset等等。

示例代码:

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log('数据库已连接');
  
  // 更新单个文档
  db.collection('customers').updateOne({ name: 'John' }, { $set: { age: 35 } }, function(err, res) {
    if (err) throw err;
    console.log('文档已更新');
    db.close();
  });

  // 更新多个文档
  db.collection('customers').updateMany({}, { $inc: { age: 1 } }, function(err, res) {
    if (err) throw err;
    console.log(res.modifiedCount + ' 个文档已更新');
    db.close();
  });
});