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

MongoDB中如何查询两个日期之间的文档(时间戳存储)

Fixing MongoDB Date Range Queries for String-Timestamp Fields

Hey there! Let's break down why your query isn't returning results and walk through the fixes.

The core issue here is a type mismatch: your creation_time field stores timestamps as strings (like "1511418850391"), but your query uses new Date() which creates Date objects. MongoDB strictly checks data types when comparing, so these two types won't match up—hence no results.

Here are three ways to resolve this:

1. Direct String Comparison (Simplest Fix)

Since your timestamp strings are numeric and fixed-length (13-digit milliseconds), their lexicographical order matches their numerical order. You can query directly with string values:

db.collection.find({
  creation_time: {
    $gte: "1511418850391", // Replace with your start timestamp string
    $lte: "1512023650391"  // Replace with your end timestamp string
  }
})

Note: This only works if all creation_time values are consistent 13-digit millisecond timestamps. If some are shorter (e.g., 10-digit seconds), this method will fail.

2. Convert Types On-the-Fly with $expr

If you prefer using Date objects in your query, use MongoDB's $expr operator to convert the string timestamp to a numeric value first, then compare it to the timestamp of your Date object:

db.collection.find({
  $expr: {
    $and: [
      { $gte: [ { $toLong: "$creation_time" }, new Date(1511418850391).getTime() ] },
      { $lte: [ { $toLong: "$creation_time" }, new Date(1512023650391).getTime() ] }
    ]
  }
})

$toLong converts the string to a numeric timestamp, and new Date(...).getTime() converts your Date object to the same numeric format for comparison.

3. Migrate to Date Type (Best Long-Term Practice)

For cleaner queries and better performance (especially with indexes), consider converting your creation_time field to MongoDB's native Date type. You can batch-update existing documents with this command:

db.collection.updateMany(
  { creation_time: { $type: "string" } }, // Target only string-type timestamps
  [
    { $set: { creation_time: { $toDate: { $toLong: "$creation_time" } } } }
  ]
)

Once converted, your original query will work perfectly:

db.collection.find({
  creation_time: {
    $gte: new Date(1511418850391),
    $lte: new Date(1512023650391)
  }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:04:05