5

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)

enter image description here

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

Nisal Edu
  • 7,237
  • 4
  • 28
  • 34
  • what library do you use to interact with `MongoDB`? – V. Panchenko Dec 08 '17 at 10:47
  • @V.Panchenko "gopkg.in/mgo.v2/bson" – Nisal Edu Dec 08 '17 at 10:48
  • please clarify your code to let us know what is `s` object (with method `DB("xxxxx")` and in what package it can be found – V. Panchenko Dec 08 '17 at 10:50
  • ok, what is `common`?) @Nisal, you should provide minimal code to let me repeat your problem and try to fix in on my machine) – V. Panchenko Dec 08 '17 at 10:55
  • @icza I tried your answer but it didn't work for me – Nisal Edu Dec 08 '17 at 11:26
  • @NisalEdu Show exactly what you've tried (edit the question). – icza Dec 08 '17 at 11:27
  • @icza I have add my mongo collection sample – Nisal Edu Dec 08 '17 at 15:07
  • @NisalEdu Have you read the answer that is marked as duplicate? Its first sentence is the key: **"You either use `Collection.FindId()` and then you pass only the id value, or you use `Collection.Find()` and then you have to specify a value with the field name too."** In your code you are calling `FindId()` and you pass a document, not an ID. – icza Dec 08 '17 at 15:12
  • @icza I tried you answer but no luck for me, I have add whole function – Nisal Edu Dec 08 '17 at 15:47
  • @NisalEdu Please define _"it didn't work for me"_. What error message do you get? Also what output do you get when you run the `db.jobs.find({_id:ObjectId("5a2a75f777e864d018131a59")})` command in the mongo client? – icza Dec 08 '17 at 15:52
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/160808/discussion-between-nisal-edu-and-icza). – Nisal Edu Dec 08 '17 at 15:54
  • @icza please vote to reopen this I didn't get any fix for my problem – Nisal Edu Dec 11 '17 at 07:05
  • 1
    Jesus christ, I got the same weird situation. FindAll is working fine, also filtering by other attributes, just failing on the ObjectId... –  Jun 11 '18 at 05:34
  • @codepushr if you find any solution please post it as an answer thanks – Nisal Edu Jun 11 '18 at 05:38
  • Found the problem. Answered below. –  Jun 11 '18 at 05:43

2 Answers2

4

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"   
  • I ran into a very similar issue with the official MongoDB mongo-driver, and found some helpful clarification and examples in [this tutorial](https://vkt.sh/go-mongodb-driver-cookbook/)... see [this question](https://stackoverflow.com/a/55446340/8620945) – Adam D Apr 02 '19 at 19:33
0

Any of above comments or answers unable to fix the issue so, What I do is,

1) Add custom generated objectId to record.

    i := bson.NewObjectId()

    rhinoJobs.id = i

    err = coll.Insert(rhinoJobs)

2) Search by that custom objectId

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(objID)).One(&job)
    if err != nil {
        print(err.Error())
        errMsg := "error occurred while getting data :" + err.Error()
        return job, errors.New(errMsg)
    }
    return job, nil
}

Think this might helps someone in future.

Useful link

Possibility of duplicate Mongo ObjectId's being generated in two different collections?

Nisal Edu
  • 7,237
  • 4
  • 28
  • 34