英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论