简体   繁体   中英

mongo-go-driver get inserted document

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM