【发布时间】:2020-02-26 17:05:17
【问题描述】:
我有以下 MongoDB 文档集合,每个文档都包含一个名为“history”的字段,其中包含一个包含字段“date”和“points”的子文档数组。
[{
history: [{
date: "2019-20-20",
points: 1,
}, {
date: "2019-20-21",
points: 1,
}, {
date: "2019-20-22",
points: 1,
}, {
date: "2019-20-23",
points: 1,
}],
}, {
history: [{
date: "2019-20-20",
points: 1,
}, {
date: "2019-20-21",
points: 2,
}, {
date: "2019-20-22",
points: 3,
}, {
date: "2019-20-23",
points: 4,
}],
}]
我不确定构建产生以下输出的查询的最佳方法是什么。对于以下示例,日期范围(含)为“2019-20-21”到“2019-20-22”。 “totalPoints”是一个新字段,其中包含该日期范围内“历史”字段中所有点的总和。
[{
history: [{
date: "2019-20-20",
points: 1,
}, {
date: "2019-20-21",
points: 1,
}, {
date: "2019-20-22",
points: 1,
}, {
date: "2019-20-23",
points: 1,
}],
totalPoints: 2,
}, {
history: [{
date: "2019-20-20",
points: 1,
}, {
date: "2019-20-21",
points: 2,
}, {
date: "2019-20-22",
points: 3,
}, {
date: "2019-20-23",
points: 4,
}],
totalPoints: 5,
}]
以下是我正在尝试做的总体思路:
User.aggregate([{
$addFields: {
totalPoints: { $sum: points in "history" field if date range between "2019-20-21" and "2019-20-22" } ,
}
}]);
我想创建一个新的“totalPoints”字段的原因是因为最终我想通过“totalPoints”字段进行排序。
【问题讨论】:
-
注意:如果要按“计算”值排序,由于
top-k排序算法,MongoDB性能会很差 -
@Valijon 如果我对计算值进行排序,您对如何提高查询性能有什么建议吗?
-
你需要做一个基准测试,MongoDb 没有为such situation 提供任何解决方案。考虑使用here描述的“堆搜索”在 MongoDB 之外进行排序@
标签: mongodb mongoose aggregation-framework