dpge74512
2017-01-21 11:26
浏览 271

无法使用mgo从MongoDB通过ObjectId获取数据

I have a PersonalAccount type as

type PersonalAccount struct {
        ID        bson.ObjectId   `json:"id" bson:"_id,omitempty"`
}

then I get a marshaled PersonalAccount through an HTTP request, and the data is unmarshaled successfully and when I check the ID type. It is a bson.ObjecID

The problem is when I try the code below:

var m PersonalAccount = unmarshaledAccount
mgo.DB("dbname").C("colname").FindId(m.ID)

It returns an error that says it is not found.

I have also tried:

var m PersonalAccount = unmarshaledAccount
mgo.DB("dbname").C("colname").Find(bson.M{"_id": m.ID})

but with no luck.

图片转代码服务由CSDN问答提供 功能建议

我的 PersonalAccount 类型为

   type PersonalAccount struct {
 ID bson.ObjectId`json:“ id” bson:“ _ id,omitempty”`
} 
   
 
 

然后我得到 通过HTTP请求编组的 PersonalAccount ,并且数据成功编组并且当我检查ID类型时,数据已解组。 它是 bson.ObjecID \ n

问题是当我尝试以下代码时:

  var m PersonalAccount = unmarshaledAccount 
mgo.DB(“ dbname”)。C(“ colname”)。  FindId(m.ID)
   
 
 

它返回一个错误,提示找不到该错误。

我也尝试过:

  var m PersonalAccount = unmarshaledAccount 
mgo.DB(“ dbname”)。C(“ colname”)。Find(bson.M {“ _ id”:m.ID}  )
   
 
 

,但没有运气。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doupingmao1903 2017-01-21 17:15
    已采纳

    You can try this

    c.FindId(bson.M{"_id": bson.ObjectIdHex("56bdd27ecfa93bfe3d35047d")})
    

    may be it will solve your problem

    打赏 评论

相关推荐 更多相似问题