Skip to content

Add database items

Use the method DatabaseManager().add_item() to add an object to the database like this:

from perseus.datamanager import DatabaseManager, Institute
db_manager = DatabaseManager()
new_institute = Institute(
name="Fachbereich Physik",
secondary_names=["Department of Physics"],
organization_id="67af0dd2616acdff502c8f88g",
)
oid = db_manager.add_item(new_institute)
if oid is not None:
...

DatabaseManager().add_item() will either return the inserted object id or None in case something went wrong.

If the object already exists in the database (meaning its object id is already used), DatabaseManager().add_item() will update the already existing database item. Have a look here: Update items

To insert many objects of the same class at once, use DatabaseManager().add_items(). All objects are written to the database in a single bulk operation, which is considerably faster than calling add_item() in a loop.

from perseus.datamanager import DatabaseManager, Institute
db_manager = DatabaseManager()
institutes = [
Institute(name="Department of Physics", secondary_names=[], organization_id="67af0dd2616acdff502c8f88"),
Institute(name="Department of Chemistry", secondary_names=[], organization_id="67af0dd2616acdff502c8f88"),
]
object_ids = db_manager.add_items(Institute, institutes)
# object_ids[0] belongs to institutes[0], object_ids[1] to institutes[1]

Parameters

cls: type[DatabaseItem]

The class of the objects. Every object in items must be an instance of exactly this class, otherwise a TypeError is raised before anything is written.

items: list[DatabaseItem]

The objects to insert. They are always inserted as new documents; use update_items() to change existing ones.

ordered: bool = False

If True, the objects are inserted in the given order and the operation stops at the first error. If False (default), all objects are attempted, even if some of them fail. See the MongoDB documentation.

Return value

The object ids of the inserted objects in the same order as items. The ids are also set on the objects themselves (item.db_id). An empty list is returned if items is empty or the database is not reachable.

Like add_item(), add_items() emits a creation event for every inserted object, see Events.