golang mongodb UPSERT with returning _id, need example

2,562 views
Skip to first unread message

Sergey Ivanov

unread,
Jan 16, 2014, 2:01:51 PM1/16/14
to golan...@googlegroups.com
Hello!

I'm using this simple line to insert new element in my mongo database 
err:= c.Insert(&req)

but I need to receive back the generated "_id" of the document. As I understand mongo has "Upsert" command for that case. Could you please provide an example with inserting new document and receiving "_id" back? 



Tim Shannon

unread,
Jan 16, 2014, 5:04:38 PM1/16/14
to golan...@googlegroups.com
I assume you are using the excellent mgo library, which has a whole user group here (https://groups.google.com/forum/#!forum/mgo-users)  that can be very helpful.

I believe what you are looking for is the UpsertId Method (http://godoc.org/labix.org/v2/mgo#Collection.UpsertId)

Then you can grab the inserted id from the ChangeInfo returned.

changeInfo.UpsertedId.(bson.ObjectId)

Carlos Salguero

unread,
Jan 16, 2014, 7:04:52 PM1/16/14
to golan...@googlegroups.com
The package bson has a method to obtain a new ObjectId (http://godoc.org/labix.org/v2/mgo/bson#NewObjectId) so, you can pre-load the _id field in your struct by doing something like;
    req.Id = bson.NewObjectId() and THEN execute the insert.

Sergey Ivanov

unread,
Jan 17, 2014, 4:32:34 AM1/17/14
to golan...@googlegroups.com
Thank you,

but what if I want the _id to be "autogenerated" by mongodb itself? 
Reply all
Reply to author
Forward
0 new messages