handling int64 numbers

31 views
Skip to first unread message

Jim Robinson

unread,
May 18, 2013, 12:06:52 AM5/18/13
to mgo-...@googlegroups.com
Hi folks,

The documentation I've read so far appears slightly vague
about how to properly handle reading int64 values out of
mongo when using mgo.

Is the proper technique something along the lines of the following,
for the example of a incrementing a sequence counter?

...
collection := session.DB(db).C(collection)

locate := bson.M{"_id": id}

change := mgo.Change{
Update:    bson.M{"$inc": bson.M{"n": 1}},
Upsert:    true,
ReturnNew: true}

result := bson.M{}

info, err := collection.Find(locate).Apply(change, &result)
...

var n int64
switch t := result["n"].(type) {
case int:
  n = int64(t)
case int32:
  n = int64(t)
case int64:
  n = t
default:
  ... error case ...
}

Jim Robinson

unread,
May 18, 2013, 7:09:51 AM5/18/13
to mgo-...@googlegroups.com
Ah, it appears that an alternative is to provide my own struct with bson: labels.

type Sequence struct {
Id string `bson:"_id"`
N  int64  `bson:"n"`
}

...

collection := session.DB(db).C(collection)

locate := bson.M{"_id": id}

change := mgo.Change{
Update:    bson.M{"$inc": bson.M{"n": 1}},
Upsert:    true,
ReturnNew: true}

result := &Sequence{}

info, err := collection.Find(locate).Apply(change, result)
...
return result.N, err

Reply all
Reply to author
Forward
0 new messages