简体   繁体   English

在 mongo-go-driver 中为 .FindOne 创建过滤器

[英]Creating a filter in mongo-go-driver for .FindOne

I'm trying to check a collection to see if there is at least one documents that match a specific set of values.我正在尝试检查一个集合以查看是否至少有一个文档与一组特定的值匹配。

I've tried reading the documentation at https://github.com/mongodb/mongo-go-driver#usage , but I can't seem to find much help there.我试过在https://github.com/mongodb/mongo-go-driver#usage阅读文档,但我似乎在那里找不到太多帮助。 I'm pretty new to MongoDB & Go, I believe that this is more a problem of my lack of experience.我对 MongoDB & Go 很陌生,我相信这更多是我缺乏经验的问题。

Here is a sample query from Studio 3T that I'm trying to run with mongo-go-driver:这是我尝试使用 mongo-go-driver 运行的来自 Studio 3T 的示例查询:

db.getCollection("events").find(
    { 
        "event.eventType" : "OSR", 
        "context.vehicleId" : NumberInt(919514), 
        "ts" : {
            "$gte" : ISODate("2019-06-21T21:38:43.022+0000")
        }
    }
).limit(1);

It seems that the context.FindOne method will do what I want (and eliminating the need for the .limit(1) ).似乎context.FindOne方法会做我想做的事情(并消除对.limit(1)的需要)。 I thought that it would be straight forward to "port" this to Go and the mongo-go-driver.我认为将它“移植”到 Go 和 mongo-go-driver 会很直接。

I can sort of make this work, for example I have the following which will find me all the OSR:我可以完成这项工作,例如我有以下内容可以找到我所有的 OSR:

var query = &bson.D{
        {"event.eventType", "OSR"},
    }

result := bson.D{}
e := collection.FindOne(context.TODO(), query).Decode(&result)

This will return me one document.这将返回给我一份文件。 Now, if I want to include the vehicleId value, and I update the query to:现在,如果我想包含vehicleId值,我将query更新为:

var query = &bson.D{
        {"event.eventType", "OSR"},
        {"context.vehicleId", 919514}, 
    }

No documents are returned.不返回任何文件。 I haven't bother to expand query to include the ts field yet.我还没有费心扩展query以包含ts字段。

I would expect at to still have at least one document returned, but nothing is showing up.我希望 at 仍然至少返回一份文档,但没有显示任何内容。 Does anybody have some tips, suggestions or guidance on what I'm doing wrong (or perhaps how I can do this better)?有没有人对我做错了什么(或者我可以如何做得更好)有一些提示、建议或指导?

Not quite sure, but have you tried with bson.M instead of bson.D ?不太确定,但是您是否尝试过使用bson.M而不是bson.D

It seems like it's working for me at least.似乎它至少对我有用。

query := &bson.M{
  "event.eventType": "OSR",
  "context.vehicleId": 919514, 
}

Please refer to the docs for more information.请参阅文档以获取更多信息。

Also, like @owlwalks said, are you sure, you're in the right collection?另外,就像@owlwalks 所说的,你确定你在正确的收藏中吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM