【问题标题】:Create View from multiple collections MongoDB从多个集合创建视图 MongoDB
【发布时间】:2019-06-01 20:55:40
【问题描述】:

我在医疗保健项目中关注 Mongo Schemas(被截断以隐藏项目敏感信息)。

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*/}

【问题讨论】:

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


    【解决方案1】:

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

    恕我直言,实现这一点的最简单方法是使用类似这样的聚合:

    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,它会自动获取所有处方、报告和事件。这有一个缺点,你不能真正正确地排序和分页......

    【讨论】:

      猜你喜欢
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-29
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      相关资源
      最近更新 更多