昨天开始学MongoDB,今天写命令行聚合的时候stage格式老是写错,这里记录一下
以下是 MongoDB 聚合查询中常用 stage 的使用格式示例:
$match
:
{ $match: { fieldName: value } }
例如:{ $match: { age: { $gt: 18 } } }
表示筛选出年龄大于 18 的文档。
$group
:
{ $group: { _id: expression, field1: { aggregationOperator: expression },... } }
例如:{ $group: { _id: "$city", totalUsers: { $sum: 1 } } }
按照城市分组,并计算每个城市的用户总数。
$project
:
{ $project: { field1: 1/0, newField: expression,... } }
例如:{ $project: { name: 1, age: 1, fullName: { $concat: ["$firstName", " ", "$lastName"] } } }
选择指定字段,并创建新字段。
$sort
:
{ $sort: { fieldName: 1/-1 } }
例如:{ $sort: { age: -1 } }
按照年龄降序排序。
$limit
:
{ $limit: number }
例如:{ $limit: 10 }
限制返回 10 个文档。
$skip
:
{ $skip: number }
例如:{ $skip: 20 }
跳过前 20 个文档。
$unwind
:
{ $unwind: "$arrayField" }
例如:{ $unwind: "$skills" }
将 skills
数组字段展开。
$lookup
:
{
$lookup: {
from: "otherCollection",
localField: "localFieldName",
foreignField: "foreignFieldName",
as: "newFieldName"
}
}
例如:{ $lookup: { from: "orders", localField: "userId", foreignField: "_id", as: "userOrders" } }
关联另一个集合。