0

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

jcoke
  • 1,555
  • 1
  • 13
  • 27
  • You can use [`dir()`](https://docs.python.org/3/library/functions.html#dir) to find out what attributes an object has! `DBRef` likely has some id attributes you can get at (and it may may in turn be there's a convenience on calling `str()` on `ObjectId`) – ti7 Mar 02 '21 at 19:07

1 Answers1

1

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
Belly Buster
  • 8,224
  • 2
  • 7
  • 20
  • is there a way to actually convert it into a dataframe instead of just retrieving the values? – jcoke Mar 02 '21 at 20:11