Example usage for com.mongodb.client MongoDatabase createCollection

List of usage examples for com.mongodb.client MongoDatabase createCollection

Introduction

In this page you can find the example usage for com.mongodb.client MongoDatabase createCollection.

Prototype

void createCollection(String collectionName);

Source Link

Document

Create a new collection with the given name.

Usage

From source file:Register.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

    // TODO add your handling code here:
    MongoClient client = new MongoClient("localhost", 27017);
    MongoDatabase db = client.getDatabase("ExpenseManager");
    MongoCollection<Document> reg = db.getCollection("Registration");
    String unm = jTextField2.getText();
    BasicDBObject query = new BasicDBObject("unm", unm);
    String pass = String.valueOf(jPasswordField1.getPassword());
    String c_pass = String.valueOf(jPasswordField2.getPassword());

    if (unm.length() == 0) {
        JOptionPane.showMessageDialog(null, "User Name is empty");
        this.setVisible(true);
    }/*from   w  w  w .  j a va2s  . co m*/

    else if (reg.find(query).iterator().hasNext()) {
        JOptionPane.showMessageDialog(null, "User Name already exist");
        this.setVisible(true);
    } else if (jPasswordField1.getPassword().length == 0 || jPasswordField2.getPassword().length == 0) {
        JOptionPane.showMessageDialog(null, "Password Field Can not be empty");
        this.setVisible(true);
    } else if (!pass.equals(c_pass)) {
        JOptionPane.showMessageDialog(null, "Passwords do not match. Please Re-enter the password");
        this.setVisible(true);
    } else {
        String name = jTextField1.getText();
        Document ins = new Document("name", name).append("unm", unm).append("pass", pass);
        reg.insertOne(ins);
        System.out.println("Document is inserted into MongoDb");
        System.out.println(pass);
        db.createCollection(unm);
        this.dispose();
        login lgn = new login();
        lgn.setVisible(true);

    }

}

From source file:bariopendatalab.db.DBAccess.java

public void createDB() {
    MongoDatabase database = client.getDatabase(DBNAME);
    database.createCollection(COLLNAME);
    MongoCollection<Document> collection = database.getCollection(COLLNAME);
    collection.createIndex(new BsonDocument("geometry", new BsonString("2dsphere")));
}

From source file:com.cognifide.aet.vs.mongodb.MongoDBClient.java

License:Apache License

/**
 * Gets MonogoDB database object. Given that autoCreate param is set to true it will auto-create database
 * with provided name (if one does not exists yet).
 *
 * @param dbName name of database//from  w  ww  . j  a v a 2  s . c  o m
 * @param autoCreate defines if database creation auto-creation should occur
 * @return MongoDB databaase object or null if base does not exists.
 */
public MongoDatabase getDatabase(String dbName, Boolean autoCreate) {
    MongoDatabase database = null;
    String lowerCaseDbName = dbName.toLowerCase();

    if (getAetsDBNames().contains(lowerCaseDbName)) {
        database = mongoClient.getDatabase(lowerCaseDbName);
    } else if (allowAutoCreate && autoCreate) {
        database = mongoClient.getDatabase(lowerCaseDbName);
        database.createCollection(MetadataDAOMongoDBImpl.METADATA_COLLECTION_NAME);
    }
    return database;
}

From source file:com.gs.obevo.mongodb.impl.MongoDbChangeAuditDao.java

License:Apache License

@Override
public void init() {
    for (PhysicalSchema physicalSchema : env.getPhysicalSchemas()) {
        MongoDatabase database = mongoClient.getDatabase(physicalSchema.getPhysicalName());
        try {/*  w  ww.  ja  va  2  s.  c  o  m*/
            database.createCollection(getAuditContainerName());
        } catch (Exception e) {
            // create if it doesn't exist already; TODO clean this up
        }
        MongoCollection<Document> collection = database.getCollection(getAuditContainerName());
        collection.createIndex(Indexes.ascending(changeNameColumn, "OBJECTNAME"));
    }
}

From source file:com.gs.obevo.mongodb.impl.MongoDbDeployExecutionDao.java

License:Apache License

@Override
public void init() {
    for (PhysicalSchema physicalSchema : env.getPhysicalSchemas()) {
        MongoDatabase database = mongoClient.getDatabase(physicalSchema.getPhysicalName());
        try {/*from   w  w  w  . j ava 2 s.com*/
            database.createCollection(deployExecutionTableName);
        } catch (Exception e) {
            // create if it doesn't exist already; TODO clean this up
        }
        //            database.createCollection(deployExecutionAttributeTableName);
        //            MongoCollection<Document> collection = database.getCollection(deployExecutionTableName);
        //            collection.createIndex(Indexes.ascending(changeNameColumn, "OBJECTNAME"));

        //            nextIdBySchema.get(physicalSchema).setValue(maxId != null ? maxId.longValue() + 1 : 1);
        // TODO set this value from DB
    }
}

From source file:com.ibm.research.mongotx.daytrader.Load.java

License:Open Source License

private static void createCollections(MongoDatabase db) throws Exception {
    db.createCollection(COL_QUOTE);

    db.createCollection(COL_HOLDING);
    MongoCollection<Document> holdingCol = db.getCollection(COL_HOLDING);
    holdingCol.createIndex(new Document(H_ACCOUNT_ACCOUNTID, true));

    db.createCollection(COL_ACCOUNTPROFILE);

    db.createCollection(COL_ACCOUNT);//from  ww w .  j  av  a2s  . c  o  m
    MongoCollection<Document> accountCol = db.getCollection(COL_ACCOUNT);
    accountCol.createIndex(new Document(A_PROFILE_USERID, true));

    db.createCollection(COL_ORDER);
    MongoCollection<Document> orderCol = db.getCollection(COL_ORDER);
    orderCol.createIndex(new Document(O_ACCOUNT_ACCOUNTID, true));
}

From source file:com.ibm.research.mongotx.lrc.LatestReadCommittedTxDB.java

License:Open Source License

public LatestReadCommittedTxDB(MongoClient client, MongoDatabase db) {
    this.client = client;
    this.db = db;
    this.db.withWriteConcern(WriteConcern.SAFE);
    if (db.getCollection(COL_SYSTEM) == null) {
        db.createCollection(COL_SYSTEM);
        this.sysCol = new MongoProfilingCollection(db.getCollection(COL_SYSTEM));
        this.sysCol.createIndex(new Document(ATTR_TX_TIMEOUT, true));
        this.sysCol.createIndex(new Document(ATTR_TX_STARTTIME, true));
    } else {/*from  w ww . j  a v  a2s . c  o  m*/
        this.sysCol = new MongoProfilingCollection(db.getCollection(COL_SYSTEM));
    }
    this.clientId = incrementAndGetLong(ID_CLIENT);
    this.isSharding = isSharding();

    getCurrentTimeInServer();

    long requestTs = System.currentTimeMillis();
    long serverTs = getCurrentTimeInServer();
    long responseTs = System.currentTimeMillis();

    this.timeGapMin = requestTs - serverTs - MAX_TIMEDIFF;
    this.timeGapMax = responseTs - serverTs + MAX_TIMEDIFF;
}

From source file:com.px100systems.data.plugin.storage.mongo.MongoDatabaseStorage.java

License:Open Source License

public void createEntity(String unitName, Collection<String> indexedFields,
        List<CompoundIndexDescriptor> compoundIndexes) {
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    db.createCollection(unitName);

    List<IndexModel> indexes = new ArrayList<>();

    for (CompoundIndexDescriptor ci : compoundIndexes) {
        Map<String, Object> fields = new HashMap<>();
        for (CompoundIndexDescriptor.Field field : ci.getFields())
            fields.put(field.getName(), field.isDescending() ? "-1" : "1");
        indexes.add(new IndexModel(new Document(fields),
                new IndexOptions().name(indexName(ci.getName())).background(true)));
    }/*from www  .jav a 2 s. c  om*/

    for (String idx : indexedFields)
        indexes.add(
                new IndexModel(new Document(idx, 1), new IndexOptions().name(indexName(idx)).background(true)));

    db.getCollection(unitName).createIndexes(indexes);
}

From source file:com.telefonica.iot.cygnus.backends.mongo.MongoBackend.java

License:Open Source License

/**
 * Creates a collection, given its name, if not exists in the given database.
 * @param dbName/*from   w ww  .  j av  a2s .  c om*/
 * @param collectionName
 * @throws Exception
 */
public void createCollection(String dbName, String collectionName) throws Exception {
    LOGGER.debug("Creating Mongo collection=" + collectionName + " at database=" + dbName);
    MongoDatabase db = getDatabase(dbName);

    try {
        db.createCollection(collectionName);
    } catch (Exception e) {
        if (e.getMessage().contains("collection already exists")) {
            LOGGER.debug("Collection already exists, nothing to create");
        } else {
            throw e;
        } // if else
    } // try catch
}

From source file:com.telefonica.iot.cygnus.backends.mongo.MongoBackend.java

License:Open Source License

/**
 * Stores in per-service/database "collection_names" collection the matching between a hash and the fields used to
 * build it./*from   ww  w .ja  va  2 s . c  om*/
 * FIXME: destination is under study
 * @param dbName
 * @param hash
 * @param isAggregated
 * @param fiwareService
 * @param fiwareServicePath
 * @param entityId
 * @param entityType
 * @param attrName
 * @param destination
 * @throws java.lang.Exception
 */
public void storeCollectionHash(String dbName, String hash, boolean isAggregated, String fiwareService,
        String fiwareServicePath, String entityId, String entityType, String attrName, String destination)
        throws Exception {
    // get the database and the collection; the collection is created if not existing
    MongoDatabase db = getDatabase(dbName);
    MongoCollection collection;

    try {
        LOGGER.debug("Creating Mongo collection=collection_names at database=" + dbName);
        db.createCollection("collection_names");
    } catch (Exception e) {
        if (e.getMessage().contains("collection already exists")) {
            LOGGER.debug("Collection already exists, nothing to create");
        } else {
            throw e;
        } // if else
    } finally {
        collection = db.getCollection("collection_names");
    } // try catch finally

    // Two updates operations are needed since MongoDB currently does not support the possibility to address the
    // same field in a $set operation as a $setOnInsert operation. More details:
    // http://stackoverflow.com/questions/23992723/ \
    //     findandmodify-fails-with-error-cannot-update-field1-and-field1-at-the-same

    // build the query
    BasicDBObject query = new BasicDBObject().append("_id", hash + (isAggregated ? ".aggr" : ""));

    // do the first update
    BasicDBObject update = buildUpdateForCollectionHash("$setOnInsert", isAggregated, fiwareService,
            fiwareServicePath, entityId, entityType, attrName, destination);
    LOGGER.debug("Updating data, database=" + dbName + ", collection=collection_names, query="
            + query.toString() + ", update=" + update.toString());
    UpdateResult res = collection.updateOne(query, update, new UpdateOptions().upsert(true));
    /*
            TECHDEBT:
            https://github.com/telefonicaid/fiware-cygnus/issues/428
            https://github.com/telefonicaid/fiware-cygnus/issues/429
                    
            if (res.getMatchedCount() == 0) {
    LOGGER.error("There was an error when storing the collecion hash, database=" + dbName
            + ", collection=collection_names, query=" + query.toString() + ", update=" + update.toString());
    return;
            } // if
                    
            // do the second update
            update = buildUpdateForCollectionHash("$set", isAggregated, fiwareService, fiwareServicePath, entityId,
        entityType, attrName, destination);
            LOGGER.debug("Updating data, database=" + dbName + ", collection=collection_names, query="
        + query.toString() + ", update=" + update.toString());
            res = collection.updateOne(query, update);
                    
            if (res.getMatchedCount() == 0) {
    LOGGER.error("There was an error when storing the collecion hash, database=" + dbName
            + ", collection=collection_names, query=" + query.toString() + ", update=" + update.toString());
            } // if
    */
}