MongoDB多表关联查询操作实例详解


本文整理自网络,侵删。

本文实例讲述了MongoDB多表关联查询操作。分享给大家供大家参考,具体如下:

Mongoose的多表关联查询

首先,我们回忆一下,MySQL多表关联查询的语句:

student表:

calss表:

通过student的classId关联进行查询学生名称,班级的数据:

SELECT student.name,student.age,class.name FROM student,class WHERE student.classId = class.id

Mongoose多表联合查询(还是以众所周知的学生、班级作为实例)

· 表结构的定义(schemas目录下)

1. student表(student.js)

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
/*定义数据模式*/
var StudentSchema = new mongoose.Schema({
  name: String,
  calssId: {
    type: Schema.Types.objectId,
    ref: 'class'
  },
  age: Number,
  number: Number,
  meta: {
    createAt: {
      type: Date,
      default: Date.now()
    },
    updateAt: {
      type: Date,
      default: Date.now()
    }
  }
  /*更新时间的*/
});
module.exports = StudentSchema;

2. class表(class.js)

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
/*定义数据模式*/
var ClassSchema = new mongoose.Schema({
  name: String,
  meta: {
    createAt: {
      type: Date,
      default: Date.now()
    },
    updateAt: {
      type: Date,
      default: Date.now()
    }
  }
  /*更新时间的*/
});
module.exports = ClassSchema;

· 生成Model(model目录下)

1. student Model(student.js)

var mongoose = require('mongoose');
var StudentSchema = require('../schemas/student');
/*通过model编译模式为模型*/
var Student = mongoose.model('student', StudentSchema);
/*导出Student模型 模块*/
module.exports = Student;

2. class Model(class.js)

var mongoose = require('mongoose');
var ClassSchema = require('../schemas/class');
/*通过model编译模式为模型*/
var Class = mongoose.model('class', ClassSchema);
/*导出Class模型 模块*/
module.exports = Class;

· Model进行数据的查询操作

1. 将静态类的方法加到Model的编译中

StudentSchema.static = {
  fetch: function(cb){
 return this
   .find({})
   .sort('meta.updateAt') //按更新的时间排序
  }
}

2. 将静态类方法加到Model中

StudentSchema.static('fetch', function(cb){
   return this
     .find({}, cb)
  .sort('meta.updateAt')
})

3. 直接调用model的find()方法

阅读剩余部分

相关阅读 >>

mongodb教程之数据操作实例

mongodb在windows平台的安装及配置方法

mongodb基础之文档操作

centos系统下mongodb安装及配置教程

mongodb索引使用详解

关于单台mongodb实例开启oplog的过程详解

mongodb的安装及配置文件选项全解

springboot系列之mongodbaggregations用法详解

mongodb 常用的crud操作语句

mongodb4.2.8备份恢复与导出导入(推荐)

更多相关阅读请进入《mongodb》频道 >>


数据库系统概念 第6版
书籍

数据库系统概念 第6版

机械工业出版社

本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...