![]() |
VOOZH | about |
In PyMongo, inserting documents into a MongoDB collection can be done using different methods. Earlier versions used the insert() method, but it is now deprecated.
The recommended and modern approach is to use:
These methods provide better control, error handling and clarity.
insert() method was originally used in older versions of PyMongo to insert both single and multiple documents into a collection. It automatically handled either a single dictionary or a list of dictionaries.
collection.insert(document)
collection.insert([document1, document2, ...])
Parameter: document representing dictionary or list of dictionaries.
Output
👁 python-mongodb-insertinsert_one() method is used to insert a single document (i.e., one record) into a collection. Automatically adds a unique _id field if not provided.
collection.insert_one(document)
Parameter: single dictionary representing the document to be inserted into the collection.
Output
👁 Imageinsert_many() method is used to insert multiple documents into a collection at once. Instead of calling insert_one() repeatedly for each document, insert_many() allows inserting a list of documents efficiently in a single operation.
collection.insert_many([doc1, doc2, doc3,....])
Parameter: [doc1, doc2, doc3,....] represents a list of dictionary to be inserted into the collection.
Output
👁 python-mongodb-insert-many1| insert() | insert_one() | insert_many() |
|---|---|---|
| Pymongo equivalent command is insert() | Pymongo equivalent command is insert_one() | Pymongo equivalent command is insert_many() |
| Deprecated in newer versions of mongo engine | Used in newer versions of mongo engine | Used in newer versions of mongo engine |
Single or multiple document can be inserted | Only one document can be inserted | Multiple documents (list of dictionary) can be inserted |
| Throws errors for write issues and write concern problems. | Throws errors for write issues and write concern problems. | Shows an error if there's a problem inserting multiple documents. |
| Compatible with db.collection.explain() to understand how MongoDB processes it internally | Not compatible with db.collection.explain() | Not compatible with db.collection.explain() |
| If ordered is True, MongoDB stops inserting when an error occurs. If ordered is False, it tries to insert all documents, even if some fail. | If a document has an error, it won't be inserted. | If ordered is True, insertion stops on error. If False, remaining documents are still inserted. |
| Returns an object with the operation's status. | Returns the inserted document's ID. | Returns IDs of inserted documents |
Related Article: