英文:
Find Documents with mongo-driver/mongo Using Expression for Value in Key/Value Pairs
问题
我正在使用https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo,并且似乎无法弄清楚如何在查找文档时插入一个键/值对的"value"表达式。我的代码如下:
cursor, err := collection.Find(context.TODO(), bson.D{{"date", "$gte: new Date((new Date().getTime() - (1000*60*60*24*100)))"}, {"enabled", true}})
我想要实现的目标是根据当前日期检索只有特定天数的旧文档。查询不会失败,但返回0个文档。日期的值是一个表达式,但如果我不用双引号括起来,Go就不会将其视为键/值对。
非常感谢任何帮助。谢谢。
英文:
I am using https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo and can't seem to figure out how to insert an expression for the "value" of one of the key/value pairs when finding documents. My code is as follows:
cursor, err := collection.Find(context.TODO(), bson.D{{"date", "$gte: new Date((new Date().getTime() - (1000*60*60*24*100)))"}, {"enabled", true}})
What I am trying to achieve is to retrieve documents that are only a certain number of days old with respect to the current date. The query doesn't fail but returns 0 documents. The value for date is an expression but if I don't surround it with double quotes, Go doesn't treat it as a key/value pair.
Any help would be greatly appreciated. Thanks.
答案1
得分: 1
您正在为筛选器的date
字段提供一个字符串值。如文档中所述,语法应为:
filter := bson.D{{"<field>", bson.D{{"<operator>", "<value>"}}}}
请尝试按照以下代码进行重构:
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"time"
)
cursor, err := collection.Find(context.TODO(), bson.D{
{"date", bson.D{
{"$gte", time.Now().AddDate(0, 0, -100)},
}},
{"enabled", true},
})
英文:
You are providing a string value to the date
field in the filter. As mentioned in the documentation, the syntax is:
filter := bson.D{{"<field>", bson.D{{"<operator>", "<value>"}}}}
Try refactoring the code as shown below:
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"time"
)
cursor, err := collection.Find(context.TODO(), bson.D{
{"date", bson.D{
{"$gte", time.Now().AddDate(0, 0, -100)},
}},
{ "enabled", true },
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论