我正在尝试使用仅包含一个条件的MGO运行一个相当简单的查询:published
字段必须小于或等于当前时间。
我在我的数据库中有一个测试文档,其创建方式如下:
db.articles.insert([{
"title": "Woo this is a test title",
"published": ISODate("2017-01-02T12:00:00Z")
}])
我的查询代码是:
now := time.Now().Format(time.RFC3339)
articlesCollection.Find(bson.M{"published": bson.M{"$lte": now}}).
Sort("-published").All(&frontPageArticles.Articles)
但我没有得到任何记录。
我对Mongo感到很自在,但对Go来说很新(因此也是mgo) - 我确信我在基本层面上做错了什么,但我不确定是什么。有人可以帮忙吗?
解决方案很简单:不要格式化你的时间,只需传递一个time.Time
值:
now := time.Now()
mgo
包将以适当的格式对时间进行编码。在你的例子中,你将时间作为string
传递,只有当MongoDB中的published
字段也是相同格式的string
(而不是MongoDB date
)时才会有效。