【发布时间】:2017-06-23 19:03:53
【问题描述】:
假设我有这 2 个巨大的文件:
[
{
_id: ....,
status: "A",
class: "DIP1A",
"created.user._id": ...,
"created.dt": ....,
"category": "private",
price: 100.00 //type double
},
{
_id: ....,
status: "A",
class: "DIP2A",
"created.user._id": ...
"created.dt": ...,
"category": "public",
price: 200.00 //type double
},
];
查询:
var pipeline = [
{
$match: {
"created.user._id": ....
}
},
{
$unwind: "$class"
},
{
$unwind: "$price"
},
{
$group: {
_id: "$class",
price: {
$sum: "$price"
},
count: {
$sum: 1
}
}
},
{
$project: {
_id: 0,
class: '$_id',
count: 1,
price: 1
}
}
];
db.myCollection.aggregate(pipeline);
问题问题:
- 不带calculate/$sum "$price"的查询,运行速度确实更快;
索引:
db.myCollection.ensureIndex({ 'created.user._id': -1 });
db.myCollection.ensureIndex({ 'created.user._id': -1, class: 1 });
db.myCollection.ensureIndex({ 'created.user._id': -1, price: 1});
性能:
- 没有 $sum calc:5 秒有大量记录。
- $sum cals:20 分钟,记录大量记录。
【问题讨论】:
-
你能添加两个查询的解释吗?要得到它,运行 db.myCollection.aggregate(pipeline, {explain: true})
标签: node.js mongodb aggregation-framework