Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does mgo not return the ID of inserted document?

Tags:

mongodb

go

mgo

According to the documentation (http://godoc.org/launchpad.net/mgo/v2) you can obtain the ID of your "Upserted" document if you use the Upsert method.

There is also an Insert method that does not provide this functionality.
Why is that? What if I want to perform an Insert instead of an Upsert? (or wouldn't ever be any valid reason to want to do that? I'm starting to wonder.)

like image 898
Sebastián Grignoli Avatar asked Aug 17 '12 16:08

Sebastián Grignoli


1 Answers

You use bson.NewObjectId() to generate an ID to be inserted.

This is how you'd insert a new document:

i := bson.NewObjectId() c.Insert(bson.M{"_id": i, "foo": "bar"}) 

Since you don't know if you're going to insert or update when you issue an Upsert, it would be superfluous to generate an ID just to drop it right after the query (in case an update happens). That's why it's generated db-side and returned to you when applicable.

like image 191
thwd Avatar answered Oct 14 '22 12:10

thwd