1个聚合查询,通常包括过滤$match、投影$project、排序$sort、分组$group四个阶段,每个阶段通过1个对象表示,多个阶段用数组包起来,如下面的示例:有月内一堆领导讲话的新闻,找出说了加薪的领导,每个领导最近说加薪的那次新闻id
db.news.aggregate([
{
$match: {
"publish_timestamp": {
$gte: 1665158400000,
$lte: 1665763199000
},
"$or": [{
"title": {
"$regex": "加薪"
}
}, {
"text": {
"$regex": "加薪"
}
}]
}
},
{
$project: {
id: "$_id",
leader: "$leader",
publish_timestamp: "$publish_timestamp"
}
},
{
$sort: {
"publish_timestamp": - 1
}
},
{
$group: {
_id: "$leader",
latest_news_id: {
$first: "$id"
}
}
}
]);