如何在单次插入中在文档的其他字段中使用生成的 id
时间:2024-04-06
浏览:162
作者:佚名
“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《如何在单次插入中在文档的其他字段中使用生成的 id》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!
问题内容
我需要创建一个文件名带有文档 id 的文件,例如(“[document_id].png”)。但数据库文档必须包含文件路径,所以基本上我正在做的事情:
insertFileDatabase() //saves database document without file path and return inserted id createFile() //create file with the inserted id and return file path updateFileDatabase() //updates database document file inserting the file path
有没有办法可以做到这一点而不需要更新文档?避免发出两个数据库请求。
解决方案
使用 MongoDB Go driver,您可以先创建 id,然后使用它进行插入。例如:
myId := primitive.NewObjectID() myPath, _ := createFile(myId) // create a file with the generated id and return file path insertFileDatabase(myId, myPath) // insert into database a document with file path and id.
请注意,此 _id 的形式为 ObjectId。objectid 很小,可能是唯一的,生成速度快且有序。 objectid 值的长度为 12 个字节。
更多信息请参阅primitive.NewObjectID
理论要掌握,实操不能落!以上关于《如何在单次插入中在文档的其他字段中使用生成的 id》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
