|
29 | 29 | from pymongo import (common, |
30 | 30 | helpers, |
31 | 31 | message) |
32 | | -from pymongo.bulk import (BulkOperationBuilder, _Bulk) |
| 32 | +from pymongo.bulk import BulkOperationBuilder, _Bulk |
33 | 33 | from pymongo.command_cursor import CommandCursor |
34 | 34 | from pymongo.cursor import Cursor |
35 | 35 | from pymongo.errors import ConfigurationError, InvalidName, OperationFailure |
@@ -495,6 +495,39 @@ def insert_one(self, document): |
495 | 495 | return InsertOneResult(self.__insert(document), |
496 | 496 | self.write_concern.acknowledged) |
497 | 497 |
|
| 498 | + def insert_many(self, documents, ordered=True): |
| 499 | + """Insert a list of documents. |
| 500 | +
|
| 501 | + :Parameters: |
| 502 | + - `documents`: A list of documents to insert. |
| 503 | + - `ordered` (optional): If ``True`` (the default) documents will be |
| 504 | + inserted on the server serially, in the order provided. If an error |
| 505 | + occurs all remaining inserts are aborted. If ``False``, documents |
| 506 | + will be inserted on the server in arbitrary order, possibly in |
| 507 | + parallel, and all document inserts will be attempted. |
| 508 | +
|
| 509 | + :Returns: |
| 510 | + An instance of :class:`~pymongo.results.InsertManyResult`. |
| 511 | + """ |
| 512 | + if not isinstance(documents, list) or not documents: |
| 513 | + raise TypeError("documents must be a non-empty list") |
| 514 | + inserted_ids = [] |
| 515 | + def gen(): |
| 516 | + """A generator that validates documents and handles _ids.""" |
| 517 | + for document in documents: |
| 518 | + if not isinstance(document, collections.MutableMapping): |
| 519 | + raise TypeError("document must be a dict or other " |
| 520 | + "subclass of collections.MutableMapping") |
| 521 | + if "_id" not in document: |
| 522 | + document["_id"] = ObjectId() |
| 523 | + inserted_ids.append(document["_id"]) |
| 524 | + yield (_INSERT, document) |
| 525 | + |
| 526 | + blk = _Bulk(self, ordered) |
| 527 | + blk.ops = [doc for doc in gen()] |
| 528 | + blk.execute(self.write_concern.document) |
| 529 | + return InsertManyResult(inserted_ids, self.write_concern.acknowledged) |
| 530 | + |
498 | 531 | def __insert(self, docs, ordered=True, |
499 | 532 | check_keys=True, manipulate=False, write_concern=None): |
500 | 533 | """Internal insert helper.""" |
|
0 commit comments