[英]mongo-go-driver get inserted document
Collection.InsertOne()
returns a *InsertOneResult
, which only contains the ID of the inserted document. Collection.InsertOne()
返回一个*InsertOneResult
,它只包含插入文档的 ID。 To get the inserted document, you have to perform another Collection.Find()
query.要获取插入的文档,您必须执行另一个
Collection.Find()
查询。 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.当前的解决方法是使用
Collection.FindOneAndUpdate()
并将Upsert
设置为 true,因为这会返回一个*SingleResult
,然后可以将其解码为一个结构体,并将其发送回客户端。
If you wish your application to have 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.其他一些数据库在服务器端生成 id,但在 MongoDB 的情况下,每个驱动程序在客户端实现 id 生成,以便在插入之前可以完全知道每个文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.