一、Aggregation-聚合查询和mysql sql语句对应
Aggregation:
参数说明:sql(Operators)
where ($match) 、group by ($group) 、having($match)、select($project)、order by($sort)、limit($limit)
sum($sum)、count($sum)、join($lookup)
SELECT cust_id, SUM(price) as total
FROM orders
WHERE status = 'A'
GROUP BY cust_id
HAVING total > 250
db.orders.aggregate([
{$match: {status: 'A'}},
{$group: {_id: "$cust_id",total: { $sum: "$price"}}},
{$match: {total: { $gt: 250}}}
])
二、更加字段长度排序
db.collection.aggregate(
[
{$project: {
"field": 1,
"field_length": { $strLenCP: "$field" }
}},
{$sort: {"field_length": -1}},
{$project: {"field_length": 0}},
]
)
本文详细介绍了MongoDB中的聚合查询操作,通过示例展示了如何使用$match、$group、$sort和$limit等操作符实现SQL中的聚合功能,如筛选、分组、求和与排序。同时,还演示了如何根据字段长度进行排序,帮助读者掌握MongoDB的数据处理能力。
1371

被折叠的 条评论
为什么被折叠?



