本文共 2820 字,大约阅读时间需要 9 分钟。
数据库可以大致分为两类:关系型数据库和非关系型数据库。关系型数据库(RDBMS)以表和行为主要存储单位,具有强大的约束和关系建模能力,典型代表包括MySQL、Oracle、DB2、SQL Server等。非关系型数据库(NoSQL)则以键值对或文档为主要存储单位,适用于处理非结构化数据,代表性数据库包括MongoDB、Cassandra、Redis等。
MongoDB是一种广泛应用的开源文档数据库系统。它以其灵活的数据模型和高性能的查询特性著称,特别适合处理处理非结构化和半结构化数据。
MongoDB的核心概念包括以下几个:
以下是一些常用的MongoDB操作指令:
show dbsuse <database_name>dbshow collections.drop()db.dropDatabase()db.collection.insertOne({ attr: value });db.collection.insertMany([{ attr: value1 }, { attr: value2 }]); db.collection.find().count();db.collection.find({ attr: value }).sort({ attr: 1 }); db.collection.update({ oldAttr: oldVal }, { $set: { newAttr: newVal } });db.collection.updateMany({ attr: value }, { $set: { newAttr: newVal } }); db.collection.remove({ _id: ObjectId("5f4f64c6bf15e4118fcf7c2d") });db.collection.deleteOne({ _id: ObjectId("5f4f64c6bf15e4118fcf7c2d") }); MongoDB支持对查询结果进行排序、限制和跳过:
排序
db.collection.find({ user: "fitz" }).sort({ user: 1 }) (1表示升序,-1表示降序) 限制
db.collection.find({}).limit(10) 限制返回的文档数量 跳过
db.collection.find({}).skip(1) 跳过前几条记录 通过设置投影参数,可以只显示需要的字段:
db.collection.find({ user: "fitz" }, { age: 1 }); Mongoose是MongoDB的一个高级框架,提供了对MongoDB进行操作的更方便的方式。它通过定义Schema来对数据库进行类型化操作。
Schema(模式)
用于定义文档的结构和约束。例如:const mongoose = require("mongoose");const Schema = mongoose.Schema;const stuSchema = new Schema({ name: String, age: Number, gender: { type: String, default: 'Male' }, address: String}); Model(模型)
Model类似于MongoDB中的集合,用于操作具体的数据。通过以下命令创建模型:const StuModel = mongoose.model('student', stuSchema); Document(文档)
Model类似于集合中的文档,Document对象是Model的实例。例如:const stuDoc = new StuModel({ name: 'Fitz', age: 20, gender: 'Female', address: 'Chenwu'}); mongoose.connect('mongodb://127.0.0.1:27017/mongoose_test', function() { console.log('数据库已连接');}); mongoose.disconnect();
StuModel.create({ name: '1', age: 10, gender: 'male', address: 'one'}); StuModel.remove({ name: '1' }); StuModel.update({ name: '2' }, { $set: { name: 'nameChange', address: 'addressChange' } }); StuModel.find({ name: 'Fitz' }).sort({ age: -1 }); const stu = new StuModel({ name: 'newStu', age: 40, gender: 'male', address: 'DG'}); stu.save(function(err) { if (!err) { console.log('修改成功'); }}); stu.remove(function(err) { if (!err) { console.log('删除成功'); }}); stu.get('age'); stu.set('address', 'China');stu.save(); 转载地址:http://tcnuz.baihongyu.com/