You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB如何查询上月记录?附等效MySQL查询实现参考

MongoDB查询上个月所有记录的实现方法

以下是两种常用实现方案,可根据业务场景选择:

方案1:日期范围查询(优先推荐)

该方案性能最优,只要createdon字段建立了索引就可以命中,避免全表扫描,逻辑是直接限定时间范围为上个月月初到当月月初:

// 计算当月1号0点
const currentMonthStart = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
// 计算上个月1号0点
const lastMonthStart = new Date(currentMonthStart.getFullYear(), currentMonthStart.getMonth() - 1, 1);

// 执行查询
db.collection.find({
  createdon: {
    $gte: lastMonthStart,
    $lt: currentMonthStart
  }
})

方案2:聚合匹配年月(和MySQL示例逻辑完全对齐)

该方案和你提供的MySQL写法逻辑一致,直接匹配时间字段的年份、月份和上个月一致,适合不需要考虑性能的小数据量场景:

适用MongoDB 3.6及以上版本

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $and: [
          // 匹配年份和上个月一致
          { $eq: [{ $year: "$createdon" }, { $year: { $dateAdd: { startDate: "$$NOW", unit: "month", amount: -1 } } }] },
          // 匹配月份和上个月一致
          { $eq: [{ $month: "$createdon" }, { $month: { $dateAdd: { startDate: "$$NOW", unit: "month", amount: -1 } } }] }
        ]
      }
    }
  }
])

适用更低版本MongoDB

不支持$dateAdd语法的低版本可以提前计算好上个月的年月再传入:

const lastMonthDate = new Date(new Date().getFullYear(), new Date().getMonth() - 1);
const lastYear = lastMonthDate.getFullYear();
// MongoDB的$month返回值为1~12,所以需要+1
const lastMonthNum = lastMonthDate.getMonth() + 1;

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $and: [
          { $eq: [{ $year: "$createdon" }, lastYear] },
          { $eq: [{ $month: "$createdon" }, lastMonthNum] }
        ]
      }
    }
  }
])

注意:请将示例中的collection替换为实际业务集合名,createdon替换为实际存储的时间字段名

内容的提问来源于stack exchange,提问作者Niyojita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 01:30:00