Stages
阶段 |
描述 |
$addField |
添加新的field |
$lookup |
与其他collection做join操作 |
$project |
选择下一阶段需要的field |
Operators
操作 |
描述 |
$cond |
条件运算 |
$arrayElemAt |
选择索引位置的元素 |
$ifNull |
当元素等于null 或者不存在时 |
Attenttion
aggregation pipline 的 stage 顺序非常的重要,对聚合操作的性能有非常大的影响。
Example
// Requires official MongoShell 3.6+
use revdol;
db.getCollection("forums").aggregate(
[
{
"$lookup" : {
"localField" : "user_id",
"from" : "users",
"foreignField" : "id",
"as" : "user_info"
}
},
{
"$addFields" : {
"user_info" : {
"$arrayElemAt" : [
"$user_info",
0.0
]
},
"forum_picture.images" : {
"$ifNull" : [
"$images",
"$forum_picture.images"
]
},
"forum_picture.thumbs" : {
"$ifNull" : [
"$thumbs",
"$forum_picture.thumbs"
]
}
}
},
{
"$project" : {
"_id" : 0.0,
"forum_id" : "$id",
"idol_id" : 1.0,
"user_id" : 1.0,
"title" : 1.0,
"content" : 1.0,
"images" : 1.0,
"nickname" : "$user_info.nickname",
"forum_picture" : 1.0
}
}
],
{
"allowDiskUse" : false
}
);
网友评论