首页 > 解决方案 > Mongodb 查询查看性能

问题描述

我的用例是在 MongoDB 中合并两个不同的集合,它们具有大致相同的业务含义,但存储在两个不同的集合中。我通过链接找到了答案

所以要合并两个集合并创建视图,我使用下一个管道

// 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。

标签: mongodbviewdatabase-performance

解决方案


我尝试执行一些性能测试,结果该方法无法在生产中使用。第一步的聚合管道尝试对两个表进行内存连接,然后执行查询。不涉及索引。


推荐阅读