Hi @Marco_Fischer and welcome to the community!!
The following sample code below would give an explanation on how to use the DBRefs in MongoDB using Python
import pymongo
from pymongo import MongoClient
from bson.dbref import DBRef
client = pymongo.MongoClient("mongodb://localhost:27017")
db = client['test']
db.authors.drop()
db.books.drop()
authors = [
{'_id': 0, 'name': 'Conan Doyle'},
{'_id': 1, 'name': 'Homer'}
]
db.authors.insert_many(authors)
books = [
{'_id': 0 ,'title': 'Ilyad', 'author': DBRef('author', 1)},
{'_id': 1 ,'title': 'Adventures', 'author': DBRef('author', 0)},
{'_id': 2 ,'title': 'Odyssey', 'author': DBRef('author', 1)}
]
db.books.insert_many(books)
books_by_conan = list(db.books.find({'author.$id': 0}))
books_by_homer = list(db.books.find({'author.$id': 1}))
print(f'Books by Conan: {books_by_conan}')
print(f'Books by Homer: {books_by_homer}')
The result of which would look like:
Books by Conan: [{ā_idā: 1, ātitleā: āAdventuresā, āauthorā: DBRef(āauthorā, 0)}]
Books by Homer: [{ā_idā: 0, ātitleā: āIlyadā, āauthorā: DBRef(āauthorā, 1)}, {ā_idā: 2, ātitleā: āOdysseyā, āauthorā: DBRef(āauthorā, 1)}]
In the example above, author.$id
is referencing the authorās _id
values.
Here using DBRef provides a slight advantage of making it explicit that the field is referencing another collection.
However, one main disadvantage is that DBRef does not work with $lookup.
Please note that as mentioned in the page Database References, unless you have a specific & compelling reason to use DBRef, itās strongly recommended to use manual references instead (for example, putting the value of the authorās _id
directly in the author field, in the example above)
I would also suggest against using DBRef or manual references to replicate a tabular database design and using it like a foreign key.
Please see the recommended MongoDB Schema Design Best Practices | MongoDB to learn more.
Thanks
Aasawari