我目前正在为一个项目使用Mongoose,我正在尝试优化一些聚合查询。
使用缓存来缓存结果对于MongoDB来说非常简单,如下所示:
const res = cache.get(key);
if (res) {
return res;
}
MyModel.aggregate([]).then(docs => {
cache.add(key, docs);
});但在我的场景中,我有一堆聚合,它们在管道的最初阶段具有类似的繁重操作
const c = MyModel.aggregate([
{$match : {},}}
{$project :{}},
{$unwind :{}},
// extra stages for c
]);
const d = MyModel.aggregate([
{$match : {},}}
{$project :{}},
{$unwind :{}},
// extra stages for d
]);我已经使用索引和allowDiskUse选项优化了我的模式,我正在寻找更好的方案。
有没有办法使用缓存机制填充管道的第一阶段,或者甚至是管道聚合的方法?MongoDB是否在阶段流水线中缓存任何结果?
将转换转移到客户端不是一个选择,因为我想从我的数据库中尽可能地使用更多的功能。提前谢谢。
发布于 2018-09-21 03:28:09
基于JohnnyHK的评论,我找到了一种可靠的方法来缓存聚合。
我在TTL indexes中使用了一个临时集合
const mongoose = require('mongoose');
const s = mongoose.Schema({
// ...
}, {timestamps: true});
s.index({createdAt: 1},{expireAfterSeconds: 3600});
const CachingModel = mongoose.model('Cache', s);
const getData = async () => {
await Model1.aggregate([
{$match : {}}
{$project :{}},
{$unwind :{}},
{$out: 'Cache'}
]);
return Promise.all([
CachingModel.aggregate([
// #1 aggregate the matching results
]),
CachingModel.aggregate([
// #2 aggregate the matching results
])
];
}https://stackoverflow.com/questions/52415247
复制相似问题