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

使用mgo执行find时间范围查询无结果,寻求技术帮助

解决mgo查询ISODate字段无结果的问题

Hey there, let's break down why your query isn't returning the test document you inserted!

问题根源

The core issue here is a type mismatch between your query value and the stored data:

  • In MongoDB, you inserted published as an ISODate (a date/time type).
  • But in your Go code, you're converting time.Now() to a string using time.RFC3339, then passing that string to the $lte condition.

MongoDB doesn't compare strings to date types using time logic—it uses lexicographical (dictionary) order instead. That's why your query isn't matching the test document, even though the stored date is in the past.

修正后的代码

Instead of converting the time to a string, pass the raw time.Time value directly. mgo automatically serializes time.Time to MongoDB's ISODate type, so the comparison will work as expected:

// Use time.Time directly, no string conversion
now := time.Now()
// Don't forget to handle potential errors!
err := articlesCollection.Find(bson.M{"published": bson.M{"$lte": now}}).
    Sort("-published").
    All(&frontPageArticles.Articles)

if err != nil {
    // Add your error handling here, e.g.:
    // log.Printf("Failed to fetch articles: %v", err)
    return
}

额外检查(以防万一)

Just to be thorough, double-check that when inserting documents via mgo, you're also using time.Time for the published field (not strings). Since your test insert uses ISODate() directly in the shell, this shouldn't be an issue here—but it's a common pitfall to watch out for in Go code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:49:51