mongo-go-driver通过_id查找文档 [英] mongo-go-driver find a document by _id

查看:234
本文介绍了mongo-go-driver通过_id查找文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过自动生成的_id字段查找文档.下面的代码不返回任何内容:

I'm trying to find a document by its auto generated _id field. Code below returns nothing:

var documentID bson.RawValue
documentID.Type = 7
documentID.Value = []byte("5c7452c7aeb4c97e0cdb75bf")
objID := documentID.ObjectID()
value := collection.FindOne(ctx, bson.M{"_id": objID})

我提供的值是我从Mongo Express获得的真实文档ID

The value I provided is a real document id I got from Mongo Express

"_id": ObjectID("5c7452c7aeb4c97e0cdb75bf")

如果您想知道为什么要打扰RawValue,我发现了使用bson.EC.ObjectID的示例,但bson包似乎没有EC类型,我还发现了一些示例,其中提到了github.com/mongodb/mongo- go-driver/bson/objectid软件包,但我也找不到该软件包.我以前是用mgo开发的,但是我是mongo-go-driver的新手,因此,如果您可以指出一种简单的方法来声明ObjectID.

In case you're wondering why I bother with RawValue, I found examples using bson.EC.ObjectID but bson package doesn't seem to have EC type, also I found some examples mentioning github.com/mongodb/mongo-go-driver/bson/objectid package, but I could not find that package either. I previously developed with mgo but I'm new to mongo-go-driver, so if you can point an easy way to declare an ObjectID.

推荐答案

正如@Carlos所述,我更改了代码,一切正常.

As @Carlos mentioned, I changed my code as this and everything works well.

objID, _ := primitive.ObjectIDFromHex("5c7452c7aeb4c97e0cdb75bf")
value := collection.FindOne(ctx, bson.M{"_id": objID})

这篇关于mongo-go-driver通过_id查找文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆