【发布时间】:2020-04-27 04:49:47
【问题描述】:
我的用例是在 MongoDB 中合并两个不同的集合,它们具有大致相同的业务含义,但存储在两个不同的集合中。 我通过link找到了答案
所以要合并两个集合并创建视图,我使用下一个管道
// Here we do a union of the employees and freelancers using a single aggregation query.
db.createView(
"employeesAndFreelancers",
"employees",
[
{ $limit: 1 }, // 2. Keep only one document of the collection.
{ $project: { _id: '$$REMOVE' } }, // 3. Remove everything from the document.
// 4. Lookup collections to union together.
{ $lookup: { from: 'employees', pipeline: [{ $match: { department: 'sales' } }], as: 'employees' } },
{ $lookup: { from: 'freelancers', pipeline: [{ $match: { department: 'sales' } }], as: 'freelancers' } },
// 5. Union the collections together with a projection.
{ $project: { union: { $concatArrays: ["$employees", "$freelancers"] } } },
// 6. Unwind and replace root so you end up with a result set.
{ $unwind: '$union' },
{ $replaceRoot: { newRoot: '$union' } }
]);
然后我想用一些简单的查询来查询视图。
db.getCollection('employeesAndFreelancers')
.find({"updated" : { "$gte" : ISODate("2018-07-22T09:45:00.000Z")}})
.limit(5)
.sort({"updated": 1})
.explain("executionStats")
源集合在updated 字段上有索引。因此对源集合的查询将产生带有索引的执行统计信息。
所以我的问题是,如果我的集合大小为 1 GB 或更大,则视图上的查询将如何表现? 它会在管道执行过程中将整个数据加载到内存中吗? 如果是,是否有可能以某种方式改进它?
MongoDB 版本是 4.0。
【问题讨论】:
标签: mongodb view database-performance