转自:http://docs.mongoing.com/manual-zh/core/aggregation-pipeline-optimization.html
$sort + $match 顺序优化¶
如果你的管道中, $sort 后面跟着 $match ,把 $match 移到 $sort 前面可以减少需要排序的对象个数。例如,如果管道中有以下两个部分:
{ $sort: { age : -1 } },
{ $match: { status: 'A' } }
During the optimization phase, the optimizer transforms the sequence to the following:
{ $match: { status: 'A' } },
{ $sort: { age : -1 } }
组合用法如下:
db.memos.aggregate(
{ $match: { status: 'P' } },
{ $sort: { age : -1 } }
)
实例如下:
db.memos.find({}) 结果如下:
{
"_id" : 1.0,
"name" : "sue",
"age" : 19.0,
"type" : 1.0,
"status" : "P",
"favorites" : {
"artist" : "Picasso",
"food" : "pizza"
},
"finished" : [
17.0,
3.0
],
"badges" : [
"blue",
"black"
],
"points" : [
{
"points" : 85.0,
"bonus" : 20.0
},
{
"points" : 85.0,
"bonus" : 10.0
}
]
}
{
"_id" : 6.0,
"name" : "abc",
"age" : 43.0,
"type" : 1.0,
"status" : "A",
"favorites" : {
"food" : "pizza",
"artist" : "Picasso"
},
"finished" : [
18.0,
12.0
],
"badges" : [
"black",
"blue"
],
"points" : [
{
"points" : 78.0,
"bonus" : 8.0
},
{
"points" : 57.0,
"bonus" : 7.0
}
]
}
{
"_id" : 7.0,
"name" : "abc",
"age" : 43.0,
"type" : 1.0,
"status" : "A",
"favorites" : {
"food" : "pizza",
"artist" : "Picasso"
},
"finished" : [
21.0,
14.0
],
"badges" : [
"black",
"blue"
],
"points" : [
{
"points" : 78.0,
"bonus" : 8.0
},
{
"points" : 57.0,
"bonus" : 7.0
}
]
}
{
"_id" : 8.0,
"name" : "sue",
"age" : 49.0,
"type" : 1.0,
"status" : "P",
"favorites" : {
"artist" : "Picasso",
"food" : "pizza"
},
"finished" : [
17.0,
3.0
],
"badges" : [
"blue",
"black"
],
"points" : [
{
"points" : 85.0,
"bonus" : 20.0
},
{
"points" : 85.0,
"bonus" : 10.0
}
]
}
$sort方法运用如下:
1、
db.memos.aggregate({ $sort: { age : -1 } })
是按age 域(字段 或 field)降序排列;
2、
db.memos.aggregate({ $sort: { age : 1 } })
是按age 域(字段 或 field)升序排列;