inserts a unit of work into MongoDB.
197302
def insert(self, collection_name, instance):
        
        assert isinstance(instance, SiteStatistics)
        collection = self.ds.connection(collection_name)
        return collection.insert_one(instance.document).inserted_id
902629
def commit(self, unit_of_work):
        
        MemoryRepository.commit(self, unit_of_work)
        if self.is_initialized:
            entity_classes_to_dump = set()
            for state in unit_of_work.iterator():
                entity_classes_to_dump.add(type(state.entity))
            for entity_cls in entity_classes_to_dump:
                self.__dump_entities(entity_cls)
387790
void insertMany(final MongoNamespace namespace,
                  final List<BsonDocument> documents) {
    this.waitUntilInitialized();

    try {
      ongoingOperationsGroup.enter();
      // Remove forbidden fields from the documents before inserting them into the local collection.
      final List<BsonDocument> docsForStorage = new ArrayList<>(documents.size());

      for (final BsonDocument document : documents) {
        docsForStorage.add(sanitizeDocument(document));
      }

      final NamespaceSynchronizationConfig nsConfig = this.syncConfig.getNamespaceConfig(namespace);
      final Lock lock = nsConfig.getLock().writeLock();
      lock.lock();
      final List<ChangeEvent<BsonDocument>> eventsToEmit = new ArrayList<>();
      try {
        getLocalCollection(namespace).insertMany(docsForStorage);
        for (final BsonDocument document : docsForStorage) {
          final BsonValue documentId = BsonUtils.getDocumentId(document);
          final ChangeEvent<BsonDocument> event =
              ChangeEvents.changeEventForLocalInsert(namespace, document, true);
          final CoreDocumentSynchronizationConfig config = syncConfig.addAndGetSynchronizedDocument(
              namespace,
              documentId
          );
          config.setSomePendingWritesAndSave(logicalT, event);
          eventsToEmit.add(event);
        }
      } finally {
        lock.unlock();
      }
      checkAndInsertNamespaceListener(namespace);
      for (final ChangeEvent<BsonDocument> event : eventsToEmit) {
        eventDispatcher.emitEvent(nsConfig, event);
      }
    } finally {
      ongoingOperationsGroup.exit();
    }
  }
395513
def add_work_item(self, work_item):
        
        with self._conn:
            self._conn.execute(
                '''
                INSERT INTO work_items
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ''', _work_item_to_row(work_item))
82427
function (connectionName, collectionName, data, cb) {

      if (data.length === 0) {
        return cb(null, []);
      }

      var connectionObject = connections[connectionName];
      var collection = connectionObject.collections[collectionName];

      // Insert a new document into the collection
      collection.insert(data, function (err, results) {
        if (err) return cb(err);
        cb(null, results);
      });
    }
322791
def insert(self, **kwargs):
        
        if self.is_valid:
            before = self.before_insert()
            if before:
                return before

            try:
                self._document['_id'] = self.insert_one(self._document)

                self.after_insert()

                return self._document
            except PyMongoException as exc:
                return PyMongoError(
                    error_message=exc.details.get(
                        'errmsg', exc.details.get('err', 'PyMongoError.')
                    ),
                    operation='insert', collection=type(self).__name__,
                    document=self._document,
                )

        return self._errors
99825
function(o, callback) {
    var self = this;

    // Validate, 
    var err = this.validateProperties(o);
    
    if (err) callback.call(self, err);
    
    else {

      // Convert object types to strings
      this.convertTypes(o);

      // Set model defaults
      this.setDefaults(o);

      // Convert `id` to `_id`
      convertMongoID(o);

      // Save data into the database
      this.driver.insertInto({
        collection: this.context,
        values: o
      }, function(err, docs) {
        if (err) callback.call(self, err, null);
        else {
          callback.call(self, null, docs[0]._id);
        }
      });
      
    }
    
  }
215311
def insert_many(cls, documents, ordered=True):
        
        return cls.collection.insert_many(documents, ordered).inserted_ids
943921
def update(self, instance):
        
        assert isinstance(instance, UnitOfWork)
        if instance.db_id:
            query = {'_id': ObjectId(instance.db_id)}
        else:
            query = {unit_of_work.PROCESS_NAME: instance.process_name,
                     unit_of_work.TIMEPERIOD: instance.timeperiod,
                     unit_of_work.START_ID: instance.start_id,
                     unit_of_work.END_ID: instance.end_id}
        self.ds.update(COLLECTION_UNIT_OF_WORK, query, instance)
        return instance.db_id
532098
function(document, callback) {
          parentId = document.parentId
          collectionName = document.parentType

          var collection = db.collection(collectionName)
            , push = {}
          push[embeddedCollectionName] = document
          collection.findAndModify({ query: { _id: parentId }, update: { $push: push }, new: true}, function(err, oldDoc) {
            callback(document)
            ChangeDispatch.notifyIdChange(parentId, document, "insert", collectionName, embeddedCollectionName)
          })
        }
54823
private function internalInsert()
    {
        if ($this->triggerEvent(self::EVENT_NAME_BEFORE_INSERT)->isCancelled()) {
            return;
        }

        $document = $this->toArray();

        // try write document
        try {
            $this
                ->collection
                ->getMongoCollection()
                ->insert($document);
        } catch (\Exception $e) {
            throw new WriteException(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }

        // set id
        $this->defineId($document['_id']);

        // after insert event
        $this->triggerEvent(self::EVENT_NAME_AFTER_INSERT);
    }
647410
def _insert(self, sock_info, docs, ordered=True, check_keys=True,
                manipulate=False, write_concern=None, op_id=None,
                bypass_doc_val=False):
        """"""
        if isinstance(docs, collections.Mapping):
            return self._insert_one(
                sock_info, docs, ordered,
                check_keys, manipulate, write_concern, op_id, bypass_doc_val)

        ids = []

        if manipulate:
            def gen():
                """Generator that applies SON manipulators to each document
                and adds _id if necessary.
                """
                _db = self.__database
                for doc in docs:
                    # Apply user-configured SON manipulators. This order of
                    # operations is required for backwards compatibility,
                    # see PYTHON-709.
                    doc = _db._apply_incoming_manipulators(doc, self)
                    if not (isinstance(doc, RawBSONDocument) or '_id' in doc):
                        doc['_id'] = ObjectId()

                    doc = _db._apply_incoming_copying_manipulators(doc, self)
                    ids.append(doc['_id'])
                    yield doc
        else:
            def gen():
                """Generator that only tracks existing _ids."""
                for doc in docs:
                    # Don't inflate RawBSONDocument by touching fields.
                    if not isinstance(doc, RawBSONDocument):
                        ids.append(doc.get('_id'))
                    yield doc

        concern = (write_concern or self.write_concern).document
        acknowledged = concern.get("w") != 0

        command = SON([('insert', self.name),
                       ('ordered', ordered)])
        if concern:
            command['writeConcern'] = concern
        if op_id is None:
            op_id = message._randint()
        if bypass_doc_val and sock_info.max_wire_version >= 4:
            command['bypassDocumentValidation'] = True
        bwc = message._BulkWriteContext(
            self.database.name, command, sock_info, op_id,
            self.database.client._event_listeners)
        if sock_info.max_wire_version > 1 and acknowledged:
            # Batched insert command.
            results = message._do_batched_write_command(
                self.database.name + ".$cmd", message._INSERT, command,
                gen(), check_keys, self.__write_response_codec_options, bwc)
            _check_write_command_response(results)
        else:
            # Legacy batched OP_INSERT.
            message._do_batched_insert(self.__full_name, gen(), check_keys,
                                       acknowledged, concern, not ordered,
                                       self.__write_response_codec_options, bwc)
        return ids
1130898
def insert(self, document):
        
        if '_id' in document:
            return self.update(document)

        # Create it and return a modified one with the id
        cursor = self.db.execute("""
            insert into %s(data) values (?)
        """ % self.name, (json.dumps(document),))

        document['_id'] = cursor.lastrowid
        return document
1007573
def insert_many(self, documents, **kwargs):
        
        self._arctic_lib.check_quota()
        return self._collection.insert_many(documents, **kwargs)
751308
def store_work_results(self, results, collection, md5):
        

        # Make sure the md5 and time stamp is on the data before storing
        results['md5'] = md5
        results['__time_stamp'] = datetime.datetime.utcnow()

        # If the data doesn't have a 'mod_time' field add one now
        if 'mod_time' not in results:
            results['mod_time'] = results['__time_stamp']

        # Fixme: Occasionally a capped collection will not let you update with a 
        #        larger object, if you have MongoDB 2.6 or above this shouldn't
        #        really happen, so for now just kinda punting and giving a message.
        try:
            self.database[collection].update({'md5':md5}, self.clean_for_storage(results), True)
        except pymongo.errors.OperationFailure:
            #self.database[collection].insert({'md5':md5}, self.clean_for_storage(results), True)
            print 'Could not update exising object in capped collection, punting...'
            print 'collection: %s md5:%s' % (collection, md5)
571635
def _insert(self, docs, ordered=True, check_keys=True,
                manipulate=False, write_concern=None, op_id=None,
                bypass_doc_val=False, session=None):
        """"""
        if isinstance(docs, abc.Mapping):
            return self._insert_one(
                docs, ordered, check_keys, manipulate, write_concern, op_id,
                bypass_doc_val, session)

        ids = []

        if manipulate:
            def gen():
                """Generator that applies SON manipulators to each document
                and adds _id if necessary.
                """
                _db = self.__database
                for doc in docs:
                    # Apply user-configured SON manipulators. This order of
                    # operations is required for backwards compatibility,
                    # see PYTHON-709.
                    doc = _db._apply_incoming_manipulators(doc, self)
                    if not (isinstance(doc, RawBSONDocument) or '_id' in doc):
                        doc['_id'] = ObjectId()

                    doc = _db._apply_incoming_copying_manipulators(doc, self)
                    ids.append(doc['_id'])
                    yield doc
        else:
            def gen():
                """Generator that only tracks existing _ids."""
                for doc in docs:
                    # Don't inflate RawBSONDocument by touching fields.
                    if not isinstance(doc, RawBSONDocument):
                        ids.append(doc.get('_id'))
                    yield doc

        write_concern = write_concern or self._write_concern_for(session)
        blk = _Bulk(self, ordered, bypass_doc_val)
        blk.ops = [(message._INSERT, doc) for doc in gen()]
        try:
            blk.execute(write_concern, session=session)
        except BulkWriteError as bwe:
            _raise_last_error(bwe.details)
        return ids
934023
def insert_many(cls, documents):
        """"""
        from mongoframes.queries import to_refs

        # Ensure all documents have been converted to frames
        frames = cls._ensure_frames(documents)

        # Send insert signal
        signal('insert').send(cls, frames=frames)

        # Prepare the documents to be inserted
        documents = [to_refs(f._document) for f in frames]

        # Bulk insert
        ids = cls.get_collection().insert_many(documents).inserted_ids

        # Apply the Ids to the frames
        for i, id in enumerate(ids):
            frames[i]._id = id

        # Send inserted signal
        signal('inserted').send(cls, frames=frames)

        return frames