How to unpack nested DBRef in Python?

759 Views Asked by At

How do you unpack nested DBRefs?

I have checked the mongodb documentation but I still do not quite understand how to unpack the alphanumeric value within the brackets.

d = { 
    "oId" : 567, 
    "notice" : [
        DBRef("noticeId", ObjectId("5f45177b93d7b757bcbd2d55"))
    ]
}

Expected Output:

oId                   notice
567 5f45177b93d7b757bcbd2d55

1

There are 1 best solutions below

1
Belly Buster On BEST ANSWER

You want the id attribute of the DBRef object. Documentation

import pandas as pd
from bson.json_util import DBRef, ObjectId

d = {
    "oId": 567,
    "notice": [
        DBRef("noticeId", ObjectId("5f45177b93d7b757bcbd2d55"))
    ]
}

data = {'oId': [d.get('oId')], 'notice': [str(d.get('notice')[0].id)]}
df = pd.DataFrame.from_dict(data)
print(df)

gives:

   oId                    notice
0  567  5f45177b93d7b757bcbd2d55