Run the pymongo insert_one command against the default database and collection
        and returne the inserted ID.
180384
def insert_one(self, *args, **kwargs):
        
        # print(f"database.collection: '{self.database.name}.{self.collection.name}'")
        result = self.collection.insert_one(*args, **kwargs)
        return result.inserted_id
427295
def insert(cls, jobs_data, queue=None, statuses_no_storage=None, return_jobs=True, w=None, j=None):
        

        now = datetime.datetime.utcnow()
        for data in jobs_data:
            if data["status"] == "started":
                data["datestarted"] = now

        no_storage = (statuses_no_storage is not None) and ("started" in statuses_no_storage)
        if no_storage and return_jobs:
            for data in jobs_data:
                data["_id"] = ObjectId()  # Give the job a temporary ID
        else:
            inserted = context.connections.mongodb_jobs.mrq_jobs.insert(
                jobs_data,
                manipulate=True,
                w=w,
                j=j
            )

        if return_jobs:
            jobs = []
            for data in jobs_data:
                job = cls(data["_id"], queue=queue)
                job.set_data(data)
                job.statuses_no_storage = statuses_no_storage
                job.stored = (not no_storage)
                if data["status"] == "started":
                    job.datestarted = data["datestarted"]
                jobs.append(job)

            return jobs
        else:
            return inserted
495689
def update(self, table_name, primary_key, instance):
        
        assert isinstance(primary_key, dict)
        assert isinstance(instance, BaseDocument)
        collection = self._db[table_name]

        # work with a copy of the document, as the direct type change of the _id field
        # is later negated by the `BaseDocument.to_json` method
        document = instance.document
        if '_id' in document:
            document['_id'] = ObjectId(document['_id'])

        update_result = collection.replace_one(filter=primary_key, replacement=document, upsert=True)
        if update_result.upserted_id:
            instance['_id'] = update_result.upserted_id
        return update_result.upserted_id
830410
def raw_query_mongo_db(kwargs, database_name, collection_name):
    # for key in kwargs:
    #    print "arg: %s: %s" % (key, kwargs[key])
    """"""
    l = []
    response_dict = {}

    try:
        mongodb_client_url = getattr(settings, 'MONGODB_CLIENT',
                                 'mongodb://localhost:27017/')
        mc = MongoClient(mongodb_client_url,document_class=OrderedDict)
        db = mc[database_name]
        transactions = db[collection_name]
        mysearchresult = transactions.find(kwargs)
        mysearchcount = mysearchresult.count()
        if mysearchcount > 0:
            response_dict['code'] = 200
            for d in mysearchresult:
                l.append(d)
            response_dict['results'] = l
    except:
        # print "Error reading from Mongo"
        # print str(sys.exc_info())
        response_dict['code'] = 400

        response_dict['type'] = "Error"
        response_dict['message'] = str(sys.exc_info())
    return response_dict
568778
def insert_query(**kw):
    
    with current_app.app_context():
        result = db.execute(text(fetch_query_string('select_query_where_name.sql')), **kw).fetchall()
        if result:
            kw['query_id'] = result[0]['id']
        else:
            result = db.execute(text(fetch_query_string('insert_query.sql')), **kw)
            kw['query_id'] = result.lastrowid
            if (not kw['query_id']):
                result = result.fetchall()
                kw['query_id']  = result[0]['id']
        db.execute(text(fetch_query_string('insert_query_node.sql')), **kw)
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
921509
def _fix_insert(self, sql, params):
        
        meta = self.query.get_meta()

        if meta.has_auto_field:
            if hasattr(self.query, 'fields'):
                # django 1.4 replaced columns with fields
                fields = self.query.fields
                auto_field = meta.auto_field
            else:
                # < django 1.4
                fields = self.query.columns
                auto_field = meta.auto_field.db_column or meta.auto_field.column

            auto_in_fields = auto_field in fields

            quoted_table = self.connection.ops.quote_name(meta.db_table)
            if not fields or (auto_in_fields and len(fields) == 1 and not params):
                # convert format when inserting only the primary key without
                # specifying a value
                sql = 'INSERT INTO {0} DEFAULT VALUES'.format(
                    quoted_table
                )
                params = []
            elif auto_in_fields:
                # wrap with identity insert
                sql = 'SET IDENTITY_INSERT {table} ON;{sql};SET IDENTITY_INSERT {table} OFF'.format(
                    table=quoted_table,
                    sql=sql,
                )

        # mangle SQL to return ID from insert
        # http://msdn.microsoft.com/en-us/library/ms177564.aspx
        if self.return_id and self.connection.features.can_return_id_from_insert:
            col = self.connection.ops.quote_name(meta.pk.db_column or meta.pk.get_attname())

            # Determine datatype for use with the table variable that will return the inserted ID
            pk_db_type = _re_data_type_terminator.split(meta.pk.db_type(self.connection))[0]

            # NOCOUNT ON to prevent additional trigger/stored proc related resultsets
            sql = 'SET NOCOUNT ON;{declare_table_var};{sql};{select_return_id}'.format(
                sql=sql,
                declare_table_var="DECLARE @sqlserver_ado_return_id table ({col_name} {pk_type})".format(
                    col_name=col,
                    pk_type=pk_db_type,
                ),
                select_return_id="SELECT * FROM @sqlserver_ado_return_id",
            )

            output = self._values_repl.format(col=col)
            sql = self._re_values_sub.sub(output, sql)

        return sql, params
955833
def insert(key, value):
    
    # Pickle the value.
    value = pickle.dumps(value, protocol=constants.PICKLE_PROTOCOL)
    # Store the value as binary data in a document.
    doc = {
        KEY_FIELD: key,
        VALUE_FIELD: Binary(value)
    }
    # Pickle and store the value with its key. If the key already exists, we
    # don't insert (since the key is a unique index), and we don't care.
    try:
        return collection.insert(doc)
    except pymongo.errors.DuplicateKeyError:
        return None
1040828
def create_sql(self, insert=False, version=False, version_fieldname=None,
                   fields=None, ec=None, compare=False):
        
        version_fieldname = version_fieldname or 'version'
        #fix when d is empty, orm will not insert record bug 2013/04/07
        if not self._key or insert:
            d = self._get_data(fields, compare=compare)
            if d:
                return rawsql(self.table.insert().values(**d),
                              ec or self.get_engine_name()) + ';'

        else:
            d = self._get_data(fields, compare=compare)
            _key = d.pop(self._primary_field)
            if d:
                _cond = self.table.c[self._primary_field] == self._key
                if version:
                    version_field = self.table.c.get(version_fieldname)
                    if version_field is None:
                        raise KindError("version_fieldname %s is not existed in Model %s" % (version_fieldname, self.__class__.__name__))
                    _version_value = getattr(self, version_fieldname, 0)
                    # setattr(self, version_fieldname, _version_value+1)
                    d[version_fieldname] = _version_value+1
                    _cond = (version_field == _version_value) & _cond

                return rawsql(self.table.update(_cond).values(**d),
                              ec or self.get_engine_name()) + ';'
        return ''
619787
public function insert($col, $doc = [], $cb = null, $params = [])
    {
        if (mb_orig_strpos($col, '.') === false) {
            $col = $this->dbname . '.' . $col;
        }

        if (!isset($doc['_id'])) {
            $doc['_id'] = new \MongoId;
        }
        if ($this->safeMode) {
            static::safeModeEnc($doc);
        }
        try {
            $this->request(
                self::OP_INSERT,
                "\x00\x00\x00\x00" . $col . "\x00" . bson_encode($doc),
                false,
                null,
                function ($conn, $reqId = null) use ($cb, $col, $params) {
                    if ($cb !== null) {
                        $this->lastError($col, $cb, $params, $conn);
                    }
                }
            );

            return $doc['_id'];
        } catch (\MongoException $e) {
            Daemon::log('MongoClient exception: ' . $e->getMessage() . ': ' . $e->getTraceAsString());
            if ($cb !== null) {
                if ($cb !== null) {
                    $cb(['$err' => $e->getMessage(), '$doc' => $doc]);
                }
            }
        }
    }
786883
def create_new_database(request):
    """"""
    name = "Create a New MongoDB Database"

    if request.method == 'POST':
        form = CreateDatabaseForm(request.POST)

        if form.is_valid():
            result = form.save()
            if "error" in result:
                messages.error(
                    request, "The database creation operation failed.")
                messages.error(request, result["error"])
            else:
                messages.success(request, "Database created.")
            return HttpResponseRedirect(reverse('djmongo_show_dbs'))
        else:
            # The form is invalid
            messages.error(
                request, _("Please correct the errors in the form."))
            return render(request,
                          'djmongo/console/generic/bootstrapform.html',
                          {'form': form,
                           'name': name})

    else:
        # this is a GET
        context = {'name': name,
                   'form': CreateDatabaseForm(
                       initial={"initial_document": '{ "foo" : "bar" }'
                                })
                   }
        return render(request, 'djmongo/console/generic/bootstrapform.html',
                      context)
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
357841
def insert(collection_name, docs, check_keys,
           safe, last_error_args, continue_on_error, opts, ctx=None):
    """"""
    if ctx:
        return _insert_compressed(
            collection_name, docs, check_keys, continue_on_error, opts, ctx)
    return _insert_uncompressed(collection_name, docs, check_keys, safe,
                                last_error_args, continue_on_error, opts)
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
421766
def insert_many(self, docs, *args, **kwargs):
        
        if self.table is None:
            self.build_table()

        if not isinstance(docs, list):
            raise ValueError(u'"insert_many" requires a list input')

        bypass_document_validation = kwargs.get('bypass_document_validation')

        if bypass_document_validation is not True:
            # get all _id in once, to reduce I/O. (without projection)
            existing = [doc['_id'] for doc in self.find({})]

        _ids = list()
        for doc in docs:

            _id = doc[u'_id'] = doc.get('_id') or generate_id()

            if bypass_document_validation is not True:
                if _id in existing:
                    raise DuplicateKeyError(
                        u'_id:{0} already exists in collection:{1}'.format(
                            _id, self.tablename
                        )
                    )
                existing.append(_id)

            _ids.append(_id)

        results = self.table.insert_multiple(docs)

        return InsertManyResult(
            eids=[eid for eid in results],
            inserted_ids=[inserted_id for inserted_id in _ids]
        )
392638
def create(source, ids, force, pid_minter=None):
    """"""
    records_deprecation_warning()

    # Make sure that all imports are done with application context.
    from .api import Record
    from .models import RecordMetadata

    pid_minter = [process_minter(minter) for minter in pid_minter or []]

    data = json.load(source)

    if isinstance(data, dict):
        data = [data]

    if ids:
        assert len(ids) == len(data), 'Not enough identifiers.'

    for record, id_ in zip_longest(data, ids):
        id_ = id_ or uuid.uuid4()
        try:
            for minter in pid_minter:
                minter(id_, record)

            click.echo(Record.create(record, id_=id_).id)
        except exc.IntegrityError:
            if force:
                current_app.logger.warning(
                    "Trying to force insert: {0}".format(id_))
                # IMPORTANT: We need to create new transaction for
                # SQLAlchemy-Continuum as we are using no auto-flush
                # in Record.get_record.
                vm = current_app.extensions['invenio-db'].versioning_manager
                uow = vm.unit_of_work(db.session)
                uow.create_transaction(db.session)
                # Use low-level database model to retrieve an instance.
                model = RecordMetadata.query.get(id_)
                rec = Record(record, model=model).commit()
                current_app.logger.info("Created new revision {0}".format(
                    rec.revision_id))
                click.echo(rec.id)
            else:
                raise click.BadParameter(
                    'Record with id={0} already exists. If you want to '
                    'override its data use --force.'.format(id_),
                    param_hint='ids',
                )
        db.session.flush()
    db.session.commit()
266320
def default_database(ctx: click.Context, _param: Parameter, value: Optional[str]):
    """"""
    if value:
        return value

    if ctx.params["repository"]:
        return os.path.join(ctx.params["repository"], DB.DEFAULT_DB_FILE)

    raise click.BadParameter("Could not guess a database location")