使用mongo-driver/mongo查找具有键/值对中值表达式的文档。

huangapple go评论95阅读模式
英文:

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{{&quot;&lt;field&gt;&quot;, bson.D{{&quot;&lt;operator&gt;&quot;, &quot;&lt;value&gt;&quot;}}}}

Try refactoring the code as shown below:

import (
	&quot;context&quot; 
	&quot;go.mongodb.org/mongo-driver/bson&quot; 
	&quot;go.mongodb.org/mongo-driver/mongo&quot;
	&quot;go.mongodb.org/mongo-driver/mongo/options&quot; 
	&quot;time&quot;
)


cursor, err := collection.Find(context.TODO(), bson.D{
	{&quot;date&quot;, bson.D{
        {&quot;$gte&quot;, time.Now().AddDate(0, 0, -100)},
	}},
	{ &quot;enabled&quot;, true },
})

huangapple
  • 本文由 发表于 2022年11月6日 23:22:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/74337152.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定