Insert an object or list of objects into a collection

    CLI Example:

    .. code-block:: bash

        salt '*' mongodb.insert '[{"foo": "FOO", "bar": "BAR"}, {"foo": "BAZ", "bar": "BAM"}]' mycollection <user> <password> <host> <port> <database>
510582
def insert(objects, collection, user=None, password=None,
           host=None, port=None, database='admin', authdb=None):
    '''
    

    '''
    conn = _connect(user, password, host, port, database, authdb)
    if not conn:
        return "Failed to connect to mongo database"

    try:
        objects = _to_dict(objects)
    except Exception as err:
        return err

    try:
        log.info("Inserting %r into %s.%s", objects, database, collection)
        mdb = pymongo.database.Database(conn, database)
        col = getattr(mdb, collection)
        ids = col.insert(objects)
        return ids
    except pymongo.errors.PyMongoError as err:
        log.error("Inserting objects %r failed with error %s", objects, err)
        return err
1126076
def user_create(name, passwd, user=None, password=None, host=None, port=None,
                database='admin', authdb=None, roles=None):
    '''
    
    '''
    conn = _connect(user, password, host, port, authdb=authdb)
    if not conn:
        return 'Failed to connect to mongo database'

    if not roles:
        roles = []

    try:
        log.info('Creating user %s', name)
        mdb = pymongo.database.Database(conn, database)
        mdb.add_user(name, passwd, roles=roles)
    except pymongo.errors.PyMongoError as err:
        log.error('Creating database %s failed with error: %s', name, err)
        return six.text_type(err)
    return True
412040
def put_object(self, cont, obj, local_file):
        '''
        
        '''
        try:
            with salt.utils.files.fopen(local_file, 'rb') as fp_:
                self.conn.put_object(cont, obj, fp_)
            return True
        except Exception as exc:
            log.error('There was an error::')
            if hasattr(exc, 'code') and hasattr(exc, 'msg'):
                log.error('    Code: %s: %s', exc.code, exc.msg)
            log.error('    Content: \n%s', getattr(exc, 'read', lambda: six.text_type(exc))())
            return False
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
1202151
def user_list(user=None, password=None, host=None, port=None, database='admin', authdb=None):
    '''
    
    '''
    conn = _connect(user, password, host, port, authdb=authdb)
    if not conn:
        return 'Failed to connect to mongo database'

    try:
        log.info('Listing users')
        mdb = pymongo.database.Database(conn, database)

        output = []
        mongodb_version = _version(mdb)

        if _LooseVersion(mongodb_version) >= _LooseVersion('2.6'):
            for user in mdb.command('usersInfo')['users']:
                output.append(
                    {'user': user['user'],
                     'roles': user['roles']}
                )
        else:
            for user in mdb.system.users.find():
                output.append(
                    {'user': user['user'],
                     'readOnly': user.get('readOnly', 'None')}
                )
        return output

    except pymongo.errors.PyMongoError as err:
        log.error('Listing users failed with error: %s', err)
        return six.text_type(err)
956833
def []=(key, value)
      obj = value.is_a?(String) ? value : YAML::dump(value)
      if exists?(key) # column already exists
        data(key).update(value: obj)
      else
        db.insert(key: key.to_s, value: obj)
      end
    end
1127208
@SuppressWarnings("unchecked")
  @Override
  public <T> void insert(Object objectToSave, String collectionName) {
    if (null == objectToSave) {
      throw new InvalidJsonDbApiUsageException("Null Object cannot be inserted into DB");
    }
    Util.ensureNotRestricted(objectToSave);
    Object objToSave = Util.deepCopy(objectToSave);
    CollectionMetaData cmd = cmdMap.get(collectionName);
    cmd.getCollectionLock().writeLock().lock();
    try {
      Map<Object, T> collection = (Map<Object, T>) collectionsRef.get().get(collectionName);
      if (null == collection) {
        throw new InvalidJsonDbApiUsageException("Collection by name '" + collectionName + "' not found. Create collection first");
      }
      Object id = Util.getIdForEntity(objectToSave, cmd.getIdAnnotatedFieldGetterMethod());
      if(encrypted && cmd.hasSecret()){
        CryptoUtil.encryptFields(objToSave, cmd, dbConfig.getCipher());
      }
      if (null == id) {
        id = Util.setIdForEntity(objToSave, cmd.getIdAnnotatedFieldSetterMethod());
      } else if (collection.containsKey(id)) {
        throw new InvalidJsonDbApiUsageException("Object already present in Collection. Use Update or Upsert operation instead of Insert");
      }

      JsonWriter jw;
      try {
        jw = new JsonWriter(dbConfig, cmd, collectionName, fileObjectsRef.get().get(collectionName));
      } catch (IOException ioe) {
        logger.error("Failed to obtain writer for " + collectionName, ioe);
        throw new JsonDBException("Failed to save " + collectionName, ioe);
      }

      boolean appendResult = jw.appendToJsonFile(collection.values(), objToSave);

      if(appendResult) {
        collection.put(Util.deepCopy(id), (T) objToSave);
      }
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
      logger.error("Error when encrypting value for a @Secret annotated field for entity: " + collectionName, e);
      throw new JsonDBException("Error when encrypting value for a @Secret annotated field for entity: " + collectionName, e);
    } finally {
      cmd.getCollectionLock().writeLock().unlock();
    }
  }
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
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
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
1007364
def kwinsert(clas,pool_or_cursor,**kwargs):
    ""
    returning = kwargs.pop('returning',None)
    fields,vals = zip(*kwargs.items())
    # note: don't do SpecialField resolution here; clas.insert takes care of it
    return clas.insert(pool_or_cursor,fields,vals,returning=returning)
841311
def insert_object_into_db_pk_known(self,
                                       obj: Any,
                                       table: str,
                                       fieldlist: Sequence[str]) -> None:
        """"""
        pkvalue = getattr(obj, fieldlist[0])
        if pkvalue is None:
            raise AssertionError("insert_object_intoto_db_pk_known called "
                                 "without PK")
        valuelist = []
        for f in fieldlist:
            valuelist.append(getattr(obj, f))
        self.db_exec(
            get_sql_insert(table, fieldlist, self.get_delims()),
            *valuelist
        )
672691
def create_mongo_db(database_name, collection_name, initial_document):
    """"""
    response_dict = {}
    try:
        mongodb_client_url = getattr(settings, 'MONGODB_CLIENT',
                                 'mongodb://localhost:27017/')
        mc = MongoClient(mongodb_client_url,document_class=OrderedDict)

        db = mc[str(database_name)]
        collection = db[str(collection_name)]

        d = json.loads(initial_document, object_pairs_hook=OrderedDict)

        collection.save(d)

    except:
        # error connecting to mongodb
        response_dict['error'] = str(sys.exc_info())

    return response_dict
724658
public void insertDocIntoMongoDBCollection(String collection, String document) {

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

    }
539862
function(argv, context, callback) {
  return MongoClient.connect(mongoHost, function(err, db) {
    if (err) { return sg.die(err, callback, 'upsertPartner.MongoClient.connect'); }

    var partnersDb  = db.collection('partners');
    var partnerId   = argvGet(argv, 'partner-id,partner');

    var item = {};

    _.each(argv, (value, key) => {
      sg.setOnn(item, ['$set', sg.toCamelCase(key)], sg.smartValue(value));
    });

    everbose(2, `Upserting partner: ${partnerId}`);
    return partnersDb.updateOne({partnerId}, item, {upsert:true}, function(err, result) {
      if (err)  { console.error(err); }

      db.close();
      return callback(err, result.result);
    });
  });
}
447925
function (soajs, combo, cb) {
        soajs.mongoDb.insert(combo.collection, combo.record, cb);
    }
295455
def insert(self, index, x):
        
        self.check_insertion(x)

        self.real_list.insert(index, x)
        self._items |= {x}