Search code examples
pythonjsonpandaspymongodbref

How to unpack nested DBRef in Python?


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


Solution

  • 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