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
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
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
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
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
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
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
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to golan...@googlegroups.com
Thank you,
but what if I want the _id to be "autogenerated" by mongodb itself?