使用mgo在查询查询中使用时间戳

问题描述 投票:1回答:1

我正在尝试使用仅包含一个条件的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) - 我确信我在基本层面上做错了什么,但我不确定是什么。有人可以帮忙吗?

mongodb go mgo
1个回答
2
投票

解决方案很简单:不要格式化你的时间,只需传递一个time.Time值:

now := time.Now()

mgo包将以适当的格式对时间进行编码。在你的例子中,你将时间作为string传递,只有当MongoDB中的published字段也是相同格式的string(而不是MongoDB date)时才会有效。

© www.soinside.com 2019 - 2024. All rights reserved.