【问题标题】:Mongo find documents sorted according to a list from another collectionMongo 查找根据另一个集合中的列表排序的文档
【发布时间】:2014-11-28 20:33:06
【问题描述】:
假设我有以下架构:
书
客户
租金
我想获取客户租借的图书列表,按租借日期排序。这样做的愚蠢方法是获取一个排序的租金列表,然后对该列表中的每一本书执行一次“查找”。
必须有更好的方法,可能使用单个查询。随意提出架构更改,例如在 Book 或 Customer 中嵌入“Rent”数组。
谢谢
【问题讨论】:
标签:
mongodb
sorting
mongoose
aggregation-framework
【解决方案1】:
使用 Mongoose 的支持参考 population 来有效地做到这一点:
Rent.find({customer_id: custid})
.sort({rentedAt: 1})
.populate('book_id')
.exec(function(err, rents) {
// The book_id property of each rents doc contains its referenced book doc.
});
Mongoose 将首先执行 Rent 查询,然后再进行第二次查询以获取所有参考书籍。
确保您的 Rent 架构将 book_id 定义为正确的引用,如下所示:
book_id: {type: Schema.Types.ObjectId, ref: 'Book' }