1. 程式人生 > 資料庫 >MongoDB多表關聯查詢操作例項詳解

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,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()方法

查詢的結果均為:

[
{
_id: '5a05222f583e5720b8660191',
name: '張三',
age: 18,
number: 11,
classId: '5a0036512b740f32e4371e66'
},
{
_id: '5a05222f583e5720b8660091',
name: '李四',
age: 19,
classId: '5a0036512b740f32e1371e66'
},
{
_id: '5a05222f583e5720b18660191',
name: '趙五',
age: 17,
classId: '5a0036512b7420f32e4371e66'
}
]

· 多表聯合查詢(學生對應班級)

StudentSchema.static = {
  findStudentWithClass: function (cb) {
    return this
      .find({})
      .populate('classId')//注意這是聯合查詢的關鍵
      .sort('meta.updateAt')
      .exec(cb)
  }
}

查詢結果:

[
{
_id: '5a05222f583e5720b8660191',
classId: {
_id: '5a0036512b740f32e4371e66',
name: '一年1班'
}
},
classId: {
_id: '5a0036512b740f32e1371e66',
name: '二年2班'
}
},
classId: {
_id: '5a0036512b7420f32e4371e66',
name: '一年2班'
}
}
]

· 由上面的例項可知,mongoose的多表聯合查詢的關鍵:

1. 資料模式結構定義需要利用關鍵字ref定義關聯

var Schema = new mongoose.Schema({
  field: {
 type: mongoose.Schema.Type.ObjectId,ref: 'model'
  }
});
Schema.static = {
  fetch: function(cb){
 return this
    .find({})
    .populate('field')
    .exec(cb)
 }
 }
var Model = mongoose.Model('model',Schema );

希望本文所述對大家MongoDB資料庫程式設計有所幫助。