Run the pymongo insert_many command against the default database and collection
        and return the list of inserted IDs.
351932
def insert_many(self, *args, **kwargs):
        
        # print(f"database.collection: '{self.database.name}.{self.collection.name}'")
        result = self.collection.insert_many(*args, **kwargs)
        return result.inserted_ids
807761
def _insert(self, tree):
        
        tablename = tree.table
        count = 0
        kwargs = {}
        batch = self.connection.batch_write(tablename, **kwargs)
        with batch:
            for item in iter_insert_items(tree):
                batch.put(item)
                count += 1
        return count
1040773
def db_list(user=None, password=None, host=None, port=None, authdb=None):
    '''
    
    '''
    conn = _connect(user, password, host, port, authdb=authdb)
    if not conn:
        return 'Failed to connect to mongo database'

    try:
        log.info('Listing databases')
        return conn.database_names()
    except pymongo.errors.PyMongoError as err:
        log.error(err)
        return six.text_type(err)
724658
public void insertDocIntoMongoDBCollection(String collection, String document) {

        DBObject dbObject = (DBObject) JSON.parse(document);
        this.dataBase.getCollection(collection).insert(dbObject);

    }
526276
def _load(db_data, db):
    
    if db.name != db_data["name"]:
        raise ValueError("dbname doesn't matches! Maybe wrong database data.")

    db.__init__(client=db._client, name=db.name)
    for col_name, col_data in iteritems(db_data["_collections"]):
        collection = db.get_collection(col_name)
        collection._documents = col_data["_documents"]
        collection._uniques = col_data["_uniques"]
        db._collections[col_name] = collection

    return db
1338088
def insert(self, table, records, create_cols=False, dtypes=None):
        
        if self._check_db() is False:
            return
        try:
            table = self.db[table]
        except Exception as e:
            self.err(e, "Can not find table " + table)
        t = type(records)
        if t == dict:
            func = table.insert
        elif t == list:
            func = table.insert_many
        else:
            msg = "Rows datatype " + \
                str(t) + " not valid: use a list or a dictionary"
            self.err(msg)
        if create_cols is True:
            try:
                func(records, ensure=True, types=dtypes)
            except Exception as e:
                self.err(e, "Can not insert create columns and insert data")
            return
        else:
            try:
                func(records, types=dtypes)
            except Exception as e:
                self.err(e, "Can not insert data")
            return
        self.ok("Rows inserted in the database")
547793
def insert_many(objects, using="default"):
    
    if not objects:
        return

    import django.db.models
    from django.db import connections
    from django.db import transaction
    con = connections[using]

    model = objects[0].__class__
    fields = [f for f in model._meta.fields
              if not isinstance(f, django.db.models.AutoField)]
    parameters = []
    for o in objects:
        params = tuple(f.get_db_prep_save(f.pre_save(o, True), connection=con)
                       for f in fields)
        parameters.append(params)

    table = model._meta.db_table
    column_names = ",".join(con.ops.quote_name(f.column) for f in fields)
    placeholders = ",".join(("%s",) * len(fields))
    con.cursor().executemany("insert into %s (%s) values (%s)"
                             % (table, column_names, placeholders), parameters)
    transaction.commit_unless_managed(using=using)
1067696
def insert_many(self, table, columns, values, limit=MAX_ROWS_PER_QUERY, execute=True):
        
        # Make values a list of lists if it is a flat list
        if not isinstance(values[0], (list, set, tuple)):
            values = []
            for v in values:
                if v is not None and len(v) > 0:
                    values.append([v])
                else:
                    values.append([None])

        # Concatenate statement
        cols, vals = get_col_val_str(columns)
        statement = 'INSERT INTO {0} ({1}) VALUES ({2})'.format(wrap(table), cols, vals)

        if execute and len(values) > limit:
            while len(values) > 0:
                vals = [values.pop(0) for i in range(0, min(limit, len(values)))]
                self._cursor.executemany(statement, vals)
                self._commit()

        elif execute:
            # Execute statement
            self._cursor.executemany(statement, values)
            self._commit()
            self._printer('\tMySQL rows (' + str(len(values)) + ') successfully INSERTED')

        # Only return statement
        else:
            return statement
1161195
def verify(self):
        
        collections = self.get_data_collections()

        allIDs = []
        for coll in collections:
            IDs = self.noteDB[coll].find({"ID": {"$exists": True}},
                                         {"ID": 1, "_id": 0})
            for ID in IDs:
                allIDs.append(int(ID["ID"]))

        query = {"currentMax": {"$exists": True}}
        maxID = int(self.noteDB['IDs'].find_one(query)["currentMax"])
        query = {"unusedIDs": {"$exists": True}}
        unusedIDs = self.noteDB['IDs'].find_one(query)["unusedIDs"]
        unusedIDs = [int(ii) for ii in unusedIDs]

        unusedIDsMatch = True
        for ID in allIDs:
            if ID in unusedIDs:
                unusedIDsMatch = False

        maxIDMatch = True
        if maxID is not max(allIDs):
            maxIDMatch = False

        if maxIDMatch and unusedIDsMatch:
            print "Database is valid"
        elif not maxIDMatch and not unusedIDsMatch:
            print "Database not valid, max ID and unused IDs are incorrent"
        elif not maxIDMatch:
            print "Database not valid, max ID is incorrent"
        elif not unusedIDsMatch:
            print "Database not valid, unusedIDs is incorrent"
1371545
def executemany(self, operation, seq_of_parameters):
        
        values_list = []
        RE_INSERT_VALUES = re.compile(
            r"\s*((?:INSERT|REPLACE)\s.+\sVALUES?\s*)" +
            r"(\(\s*(?:%s|%\(.+\)s)\s*(?:,\s*(?:%s|%\(.+\)s)\s*)*\))" +
            r"(\s*(?:ON DUPLICATE.*)?);?\s*\Z",
            re.IGNORECASE | re.DOTALL)

        m = RE_INSERT_VALUES.match(operation)
        if m:
            q_prefix = m.group(1) % ()
            q_values = m.group(2).rstrip()

            for parameters in seq_of_parameters[:-1]:
                values_list.append(q_values % _escaper.escape_args(parameters))
            query = '{} {};'.format(q_prefix, ','.join(values_list))
            return self._db.raw(query)
        for parameters in seq_of_parameters[:-1]:
            self.execute(operation, parameters, is_response=False)
278637
def update_many(cls, filter, update, upsert=False):
        
        return cls.collection.update_many(filter, update, upsert).raw_result
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
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
1211892
def _insert(self, namespace, stream, events, configuration):
    
    max_items = configuration['max_items']
    for _id, event in events:
      while len(self.db[namespace][stream]) >= max_items:
        self.db[namespace][stream].pop(0)
      bisect.insort(self.db[namespace][stream], Event(_id, event))
1047269
def find(self, *args, **kwargs):
        
        # print(f"database.collection: '{self.database.name}.{self.collection.name}'")
        self.print_cursor(self.collection.find(*args, **kwargs))
31427
def iter_insert_items(tree):
    
    if tree.list_values:
        keys = tree.attrs
        for values in tree.list_values:
            if len(keys) != len(values):
                raise SyntaxError(
                    "Values '%s' do not match attributes " "'%s'" % (values, keys)
                )
            yield dict(zip(keys, map(resolve, values)))
    elif tree.map_values:
        for item in tree.map_values:
            data = {}
            for (key, val) in item:
                data[key] = resolve(val)
            yield data
    else:
        raise SyntaxError("No insert data found")
99715
def event_return(events):
    '''
    
    '''
    conn, mdb = _get_conn(ret=None)

    if isinstance(events, list):
        events = events[0]

    if isinstance(events, dict):
        log.debug(events)

        if PYMONGO_VERSION > _LooseVersion('2.3'):
            mdb.events.insert_one(events.copy())
        else:
            mdb.events.insert(events.copy())