gpt4 book ai didi

mongodb - 在带有 mgo 的查找查询中使用时间戳

转载 作者:IT王子 更新时间:2023-10-29 02:02:25 25 4
gpt4 key购买 nike

我正在尝试使用仅包含一个条件的 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)。

关于mongodb - 在带有 mgo 的查找查询中使用时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48062148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com