本文介绍了无法在golang中通过ObjectId获取mongodb记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过使用以下代码来获取ObjectId的mongodb记录,但仍通过err.Error()

不断获取未找到

以下是我的mongo收集示例

{ "_id" : ObjectId("5a2a75f777e864d018131a59"), "callDate" : "22/12/2017", "time" : "16.25", "callType" : "a", "position" : "aaa", "description" : "aaaaaa", "qty" : 2, "estimatedDuration" : 2.3, "estimatedOvertime" : 3.44, "rate" : 4, "laborExtension" : 3 }
{ "_id" : ObjectId("5a2a75f877e864d018131a5b"), "callDate" : "22/12/2017", "time" : "16.25", "callType" : "a", "position" : "aaa", "description" : "aaaaaa", "qty" : 2, "estimatedDuration" : 2.3, "estimatedOvertime" : 3.44, "rate" : 4, "laborExtension" : 3 }
{ "_id" : ObjectId("5a2a75fa77e864d018131a5d"), "callDate" : "22/12/2017", "time" : "16.25", "callType" : "a", "position" : "aaa", "description" : "aaaaaa", "qty" : 2, "estimatedDuration" : 2.3, "estimatedOvertime" : 3.44, "rate" : 4, "laborExtension" : 3 }

以下是我的模特

type RhinoJobs struct { 
ID                bson.ObjectId  `db:"id" json:"id" bson:"_id"` 
CallDate          string  `db:"call_date" json:"callDate" bson:"callDate"` 
Time              string  `db:"time" json:"time" bson:"time"` 
CallType          string  `db:"call_type" json:"callType" bson:"callType"` 
Position          string  `db:"position" json:"position" bson:"position"` 
Description       string  `db:"description" json:"description" bson:"description"` 
Qty               int     `db:"qty" json:"qty" bson:"qty"` 
EstimatedDuration float64 `db:"estimated_duration" json:"estimatedDuration" bson:"estimatedDuration"` 
EstimatedOvertime float64 `db:"estimated_overtime" json:"estimatedOvertime" bson:"estimatedOvertime"` 
Rate              float64 `db:"rate" json:"rate" bson:"rate"` 
LaborExtension    float64 `db:"labor_extension" json:"laborExtension" bson:"laborExtension"` 
} 

我想按对象ID搜索这些记录

"gopkg.in/mgo.v2"

func GetMongoSession() (*mgo.Session, error) {
    if mgoSession == nil {
        var err error
        mgoSession, err = mgo.Dial(mongoConnectionUrl)
        if err != nil {
            return nil, err
        }
    }
    return mgoSession.Clone(), nil
}



func GetJobByID(objID string) (models.RhinoJobs, error) {
    var job models.RhinoJobs
    s, err := commons.GetMongoSession()
    if err != nil {
        errMsg := "error occurred while creating mongoDB connection stack:" + err.Error()
        print(err.Error())
        return job, errors.New(errMsg)
    }
    defer s.Close()
    err = s.DB("rhino").C("jobs").FindId(bson.ObjectIdHex("5a2a75f777e864d018131a59")).One(&job)
    if err != nil {
        print(err.Error())
        errMsg := "error occurred while getting data :" + err.Error()
        return job, errors.New(errMsg)
    }
    return job, nil
}

但是当我尝试通过以下代码获取所有收集记录时,它会很好地运行

err := s.DB("rhino").C("jobs").Find(nil).All(&jobs)

我还检查了SO Q& A,但没有成功

使用_id从golang查询mongodb存储在数组中

如何在golang和mongodb中按ID查找

无法检索"_id"将mgo与golang结合使用

解决方案

我遇到了完全相同的问题,我的问题是我最近切换到了新的mgo fork(正在积极开发中),并且混淆了依赖项. /p>

我基本上将globalsign TOGETHER中的mgo与gopkg.in中的旧bson一起使用.请检查您的依赖项!

"github.com/globalsign/mgo"
"gopkg.in/mgo.v2/bson"

这是错误的!

应该是:

"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"   

I'm try to get mongodb record by ObjectId by using following code, but keep getting not found by err.Error()

Following is my mongo collection sample

{ "_id" : ObjectId("5a2a75f777e864d018131a59"), "callDate" : "22/12/2017", "time" : "16.25", "callType" : "a", "position" : "aaa", "description" : "aaaaaa", "qty" : 2, "estimatedDuration" : 2.3, "estimatedOvertime" : 3.44, "rate" : 4, "laborExtension" : 3 }
{ "_id" : ObjectId("5a2a75f877e864d018131a5b"), "callDate" : "22/12/2017", "time" : "16.25", "callType" : "a", "position" : "aaa", "description" : "aaaaaa", "qty" : 2, "estimatedDuration" : 2.3, "estimatedOvertime" : 3.44, "rate" : 4, "laborExtension" : 3 }
{ "_id" : ObjectId("5a2a75fa77e864d018131a5d"), "callDate" : "22/12/2017", "time" : "16.25", "callType" : "a", "position" : "aaa", "description" : "aaaaaa", "qty" : 2, "estimatedDuration" : 2.3, "estimatedOvertime" : 3.44, "rate" : 4, "laborExtension" : 3 }

Following is my model

type RhinoJobs struct { 
ID                bson.ObjectId  `db:"id" json:"id" bson:"_id"` 
CallDate          string  `db:"call_date" json:"callDate" bson:"callDate"` 
Time              string  `db:"time" json:"time" bson:"time"` 
CallType          string  `db:"call_type" json:"callType" bson:"callType"` 
Position          string  `db:"position" json:"position" bson:"position"` 
Description       string  `db:"description" json:"description" bson:"description"` 
Qty               int     `db:"qty" json:"qty" bson:"qty"` 
EstimatedDuration float64 `db:"estimated_duration" json:"estimatedDuration" bson:"estimatedDuration"` 
EstimatedOvertime float64 `db:"estimated_overtime" json:"estimatedOvertime" bson:"estimatedOvertime"` 
Rate              float64 `db:"rate" json:"rate" bson:"rate"` 
LaborExtension    float64 `db:"labor_extension" json:"laborExtension" bson:"laborExtension"` 
} 

I want to get search these record by object id

"gopkg.in/mgo.v2"

func GetMongoSession() (*mgo.Session, error) {
    if mgoSession == nil {
        var err error
        mgoSession, err = mgo.Dial(mongoConnectionUrl)
        if err != nil {
            return nil, err
        }
    }
    return mgoSession.Clone(), nil
}



func GetJobByID(objID string) (models.RhinoJobs, error) {
    var job models.RhinoJobs
    s, err := commons.GetMongoSession()
    if err != nil {
        errMsg := "error occurred while creating mongoDB connection stack:" + err.Error()
        print(err.Error())
        return job, errors.New(errMsg)
    }
    defer s.Close()
    err = s.DB("rhino").C("jobs").FindId(bson.ObjectIdHex("5a2a75f777e864d018131a59")).One(&job)
    if err != nil {
        print(err.Error())
        errMsg := "error occurred while getting data :" + err.Error()
        return job, errors.New(errMsg)
    }
    return job, nil
}

But when I try to get all collection records by following code it works fine

err := s.DB("rhino").C("jobs").Find(nil).All(&jobs)

I also check following SO Q&A but didn't work

Querying mongodb from golang using the _id stored in an array

How to find by id in golang and mongodb

Cannot retrieve "_id" value using mgo with golang

解决方案

I had the exact same problem, my issue was that I recently switched to the new mgo fork (which is being actively developed) and I mixed up dependencies.

I basically used mgo from globalsign TOGETHER with the old bson from gopkg.in. Please check your dependencies!

"github.com/globalsign/mgo"
"gopkg.in/mgo.v2/bson"

This is wrong!!

Instead it should be:

"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"   

这篇关于无法在golang中通过ObjectId获取mongodb记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 12:20