MongoDB聚合查询常用的八个stage格式

昨天开始学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" } } 关联另一个集合。

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值