如何将一行拆分为不同的集合,每个集合存储第一个集合的 _id 作为参考

发布于 2024-12-10 03:27:03 字数 704 浏览 2 评论 0原文

给定以下具有四个属性的行:

{ 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风情万种。 2024-12-17 03:27:03

驱动程序实际上负责生成 ObjectId 值,因此它相当简单(下面我假设您的数据库存储在 python 变量“db”中):

import bson

myrow = { att1 : "att1", att2 : "att2", att3 : "att3", att4 : "att4"}

ref_id = bson.ObjectId()
db.collectionA.insert({att1:myrow['att1'], att2:myrow['att2'], _id:ref_id})
db.collectionB.insert({att3:myrow['att3'], att4:myrow['att4'], ref_id:ref_id})

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'):

import bson

myrow = { att1 : "att1", att2 : "att2", att3 : "att3", att4 : "att4"}

ref_id = bson.ObjectId()
db.collectionA.insert({att1:myrow['att1'], att2:myrow['att2'], _id:ref_id})
db.collectionB.insert({att3:myrow['att3'], att4:myrow['att4'], ref_id:ref_id})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文