简体   繁体   中英

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. I'm pretty new to MongoDB & Go, I believe that this is more a problem of my lack of experience.

Here is a sample query from Studio 3T that I'm trying to run with mongo-go-driver:

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) ). I thought that it would be straight forward to "port" this to Go and the mongo-go-driver.

I can sort of make this work, for example I have the following which will find me all the 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:

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.

I would expect at to still have at least one document returned, but nothing is showing up. 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 ?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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