mongodb - 如何在单个插入中在文档的其他字段中使用生成的 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 驱动程序,您可以先创建 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
推荐阅读
- c# - C#如何找到随机数数组中最小数字的出现次数?
- gstreamer - 是否可以使用 GStreamer 管道构建简单的音高标签系统?
- asynchronous - 如何仅在从漫长的过程中填充对象后才返回对象集合
- json - 如何解析来自 API 的单值 JSON 响应?
- python - pyspark 数据框将 json 列旋转到新列
- vue.js - 使用 Apollo 和 GraphQL 缓存而不是 Vuex?
- node.js - Express:PayloadTooLargeError 试图读取包含大 JSON 的 POST 正文,尽管设置了限制
- typescript - 从 WebView 访问 VS Code api
- python - 更正 re.compile 以消除句点,但为逗号添加空格
- python - 熊猫:在同一图中绘制线和条形图_使用自定义索引_