Insert into mongodb with DBRef

How to insert a new object into mongodb using pymongo with reference to other objects using DBRef.

In mongodb, external object reference is like below:

{
    "external_object": {
        "$ref": "collection_where_external_object_exists",
        "$id": Object("xxxxxx")
    }
}

With bson.dbref.DBRef, above data can be posted to mongodb like below:

from bson.dbref import DBRef

{
    "external_object": DBRef(collection="collection_where_external_object_exists",
    id="xxxxxx")
}

References

mongodb nosql python