1
votes

Collection.InsertOne() returns a *InsertOneResult, which only contains the ID of the inserted document. To get the inserted document, you have to perform another Collection.Find() query. Is there a way to do this in a single step?

A current work around is to use Collection.FindOneAndUpdate() with Upsert set to true, as this returns a *SingleResult that can then be decoded into a struct, and sent back to the client.

1
InsertOne() expects the document to be inserted, so you must have it when calling it. The only "optional" thing is the _id which is returned to you in the InsertOneResult. Please explain what you want to achieve.icza
I was just wondering if you could have the entire bson document returned after an insert. I'm just used to this with other orms.I_A
@I_A I have the exact same issue - did you find a decent solution for this?Corel

1 Answers

1
votes

If you wish your application to have the complete document:

  • Generate the _id on client side
  • Insert the complete document

At that point the document you have is exactly the document that the database has, and returning it from the insert is pointless.

Some other databases generate ids on the server side, but in case of MongoDB each driver implements id generation on the client side such that each document can be completely known prior to the insert.