使用mgo执行find时间范围查询无结果,寻求技术帮助
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
publishedas anISODate(a date/time type). - But in your Go code, you're converting
time.Now()to a string usingtime.RFC3339, then passing that string to the$ltecondition.
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

