2019-07-02 17:09
浏览 358


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, 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:

        "event.eventType" : "OSR", 
        "context.vehicleId" : NumberInt(919514), 
        "ts" : {
            "$gte" : ISODate("2019-06-21T21:38:43.022+0000")

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)?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • doulie0178 2019-07-03 11:08

    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?

    解决 无用
    打赏 举报

相关推荐 更多相似问题