doudou8081 2019-07-02 17:09
浏览 371
已采纳

在mongo-go-driver中为.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)?

  • 写回答

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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失