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

MongoDB基于日期过滤数据:添加180天时间条件查询

MongoDB查询:筛选包含180天内时间戳的bugs文档

你的需求是在原有查询基础上,额外筛选出bugs字段中至少存在一个时间戳距今不超过180天的文档。由于bugs的键是动态时间戳,需要用聚合表达式处理这些动态键,具体实现如下:

1. MongoDB Shell 查询语句

// 计算180天前的时间戳
const eighteenDaysAgo = new Date(Date.now() - 180 * 24 * 60 * 60 * 1000);

db.open_sr.find({
  // 保留原有非空判断
  "bugs": {"$ne": {}, "$exists": true},
  // 新增聚合表达式条件
  "$expr": {
    "$gt": [
      {
        "$size": {
          "$filter": {
            // 将bugs对象转为[{k: 时间戳, v: bug编号}]的数组
            "input": {"$objectToArray": "$bugs"},
            // 筛选出时间戳在180天内的元素
            "cond": {
              "$gte": [
                {"$toDate": "$$this.k"}, // 将字符串时间戳转为Date类型
                eighteenDaysAgo
              ]
            }
          }
        }
      },
      0 // 判断筛选后数组长度大于0,即存在符合条件的时间戳
    ]
  }
})

2. Python 脚本实现

如果是在Python中使用pymongo,代码如下:

from datetime import datetime, timedelta
from pymongo import MongoClient

# 连接MongoDB(根据实际配置调整)
client = MongoClient("mongodb://localhost:27017/")
db = client.your_database_name  # 替换为你的数据库名

# 计算180天前的时间
eighteen_days_ago = datetime.now() - timedelta(days=180)

query = {
    "bugs": {"$ne": {}, "$exists": True},
    "$expr": {
        "$gt": [
            {
                "$size": {
                    "$filter": {
                        "input": {"$objectToArray": "$bugs"},
                        "cond": {
                            "$gte": [
                                {"$toDate": "$$this.k"},
                                eighteen_days_ago
                            ]
                        }
                    }
                }
            },
            0
        ]
    }
}

# 执行查询并遍历结果
for doc in db.open_sr.find(query):
    print(doc)

关键逻辑说明

  • $objectToArray: 将bugs键值对对象转换为数组结构,方便遍历处理动态时间戳键。
  • $filter: 遍历转换后的数组,筛选出时间戳转成Date类型后,晚于180天前的元素。
  • $size: 统计筛选后符合条件的元素数量,判断数量大于0则说明文档满足要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 01:43:01