MongoDB在Go中的逻辑运算符不起作用。

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

MongoDB Logical operators in go not working

问题

我正在尝试查询我的Mongo数据库中的文档。我已经分别尝试了每个条件,都能正常工作,但是当使用and运算符时,没有选择任何内容。我想要能够指定一个时间范围(以Unix时间戳格式),并返回所有在此范围内的事件。同时,我也希望能够指定一个userid,以便只选择由单个用户创建的事件。

// 指定过滤器
filter := bson.D{
	{
		"$and",
		bson.A{
			bson.D{{"start", bson.D{{"$gte", datamap.Schedule.Start}}}},
			bson.D{{"end", bson.D{{"$lte", datamap.Schedule.End}}}},
			bson.D{{"userid", datamap.Schedule.UserID}},
		},
	},
}

cursor, err := collection.Find(context.TODO(), filter)
if err != nil {
	panic(err)
}
英文:

I am attempting to query documents in my mongo database. I've tried each condition individually and that works fine, however when using the and operator nothing is selected. I want to be able to specify a range of time (in unix timestamp format) and return all events that fall in between. Its also important that I can specify a userid so only events created by a single user will be selected.

// Specify the filter
filter := bson.D{
	{
		"$and",
		bson.A{
			bson.D{{"start", bson.D{{"$gte", datamap.Schedule.Start}}}},
			bson.D{{"end", bson.D{{"lte", datamap.Schedule.End}}}},
			bson.D{{"userid", datamap.Schedule.UserID}},
		},
	},
}

cursor, err := collection.Find(context.TODO(), filter)
if err != nil {
	panic(err)
}

答案1

得分: 2

我刚刚自己进行了一次测试,并确认下面的拼写错误是原因:

bson.D{{"end", bson.D{{"lte", datamap.Schedule.End}}}},

lte 应该是 $lte

没有前导的 $,生成的查询语句是:

{
  "$and": [
    { "start": { "$gte": 123 } },
    { "end": { "lte": 456 } },
    { "userid": "the-id" }
  ]
}

这意味着,除了其他表达式之外,文档应该有一个嵌入的 end 字段,其 lte 字段值为 456。显然,没有一个文档具有 end.lte 字段,因此没有选择任何内容。

英文:

I just had a test myself, and confirm that it's the typo below to blame:

bson.D{{"end", bson.D{{"lte", datamap.Schedule.End}}}},

lte should be $lte.

Without the leading $, the generated query is:

{
  "$and": [
    { "start": { "$gte": 123 } },
    { "end": { "lte": 456 } },
    { "userid": "the-id" }
  ]
}

It means that, besides other expressions, the documents should have an embedded document end whose lte field value is 456. Obviously, there is not a document has the field end.lte, so nothing is selected.

huangapple
  • 本文由 发表于 2023年5月10日 12:38:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76214938.html
匿名

发表评论

匿名网友

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

确定