开发者

How to split a row into different collections with each store the _id of the first collection as reference

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开发者_StackOverflow社区("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?


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})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜