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

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

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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?