如何将一行拆分为不同的集合,每个集合存储第一个集合的 _id 作为参考
给定以下具有四个属性的行:
{ att1 : "att1", att2 : "att2", att3 : "att3", att4 : "att4"}
我想将此行存储到 MongoDB 中的两个集合中。的 _id collectionA 将用作关系数据库中的外键。
如何使用 pymongo 在 MongoDB 中高效地实现这一点?
collectionA
{
"att1" : "att1"
"att2" : "att2"
"_id" : ObjectID("4e95e41a1d41c823d5000001")
}
collectionB
{
"att3" : "att3"
"att4" : "att4"
"ref_id" : ObjectID("4e95e41a1d41c823d5000001")
"_id" : ObjectId("4e95f81587ebf9f190c3cc4e")
}
我已经看到这里发布了一个针对 JavaScript 的解决方案。然而,每一次, 我们必须先将文档插入到collectionA中,然后查询其_id 刚刚插入的文档用于进一步操作。有更好的办法吗?
Given the following row with four attributes:
{ att1 : "att1", att2 : "att2", att3 : "att3", att4 : "att4"}
I want to store this row into two collections in MongoDB. The _id of
the collectionA will be used as a foreign key in relational DB.
How to efficiently implement this in MongoDB with pymongo?
collectionA
{
"att1" : "att1"
"att2" : "att2"
"_id" : ObjectID("4e95e41a1d41c823d5000001")
}
collectionB
{
"att3" : "att3"
"att4" : "att4"
"ref_id" : ObjectID("4e95e41a1d41c823d5000001")
"_id" : ObjectId("4e95f81587ebf9f190c3cc4e")
}
I have seen a solution posted here for JavaScript. However, each time,
we have to insert the document to collectionA first and then query the _id of
the just inserted document for further operations. Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
驱动程序实际上负责生成 ObjectId 值,因此它相当简单(下面我假设您的数据库存储在 python 变量“db”中):
The driver is actually responsible for generating the ObjectId value, so it's fairly straightforward (below I assume your database is stored in the python variable 'db'):