从多个集合MongoDB创建视图

时间:2019-01-07 07:35:47

标签: node.js mongodb mongoose mongodb-query aggregation-framework

我从医疗保健项目中遵循了Mongo Schema(被截断以隐藏项目敏感信息)。

let PatientSchema = mongoose.Schema({_id:String})
let PrescriptionSchema = mongoose.Schema({_id:String, patient: { type: Number, ref: 'Patient', createdAt:Date }})
let ReportSchema = mongoose.Schema({_id:String, patient: { type: Number, ref: 'Patient', createdAt:Date }})
let EventsSchema = mongoose.Schema({_id:String, patient: { type: Number, ref: 'Patient', createdAt:Date }})

移动和网络应用程序中有一个ui屏幕,称为“健康历史记录”,在这里我需要对根据createAt排序的处方,报告和事件中的条目进行分页。因此,我正在构建一个REST端点来获取这种异构数据。我该如何实现。是否可以从多个架构模型创建“视图”,以便我不会加载所有3个架构的内容来获取一页条目。我的“视图”的架构应如下所示,以便我可以对其进行其他查询(例如,查找上一个报告)

{recordType:String,/* prescription/report/event */, createdDate:Date, data:Object/* content from any of the 3 tables*/}

1 个答案:

答案 0 :(得分:0)

我可以想到三种方法来做到这一点。

实现这一目标的最简单方法是使用以下聚合:

db.Patients.aggregate([
 {$match : {_id: <somePatientId>},
 {
   $lookup:
     {
       from: Prescription, // replicate this for Report and Event,
       localField: _id,
       foreignField: patient,
       as: prescriptions // or reports or events,
     }
  },
  { $unwind: prescriptions }, // or reports or events
  { $sort:{ $createDate : -1}},
  { $skip: <positive integer> },
  { $limit: <positive integer> },
])

您将不得不对其进行进一步调整,以获取正确的createdDate。为此,您可能需要查看$ replaceRoot运算符。

第二个选项是创建一个新的“元”集合,该集合可保存您的实际事件列表,但仅使用refPath处理这三个事件,同时保留对患者以及实际事件的引用不同的事件类型。这个解决方案是最优雅的,因为它使查询数据的方式更加容易,并且性能也可能更高。尽管如此,它仍然需要您创建和处理另一个集合,这就是为什么我不建议将此作为主要解决方案的原因,因为我不知道您是否可以创建新集合。

作为最后一个选择,您可以在Patient中创建virtual populate fields,该功能会自动提取所有处方,报告和事件。这样做的缺点是您无法真正正确地排序和分页...

相关问题