Example usage for com.mongodb.client MongoDatabase getCollection

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

Introduction

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

Prototype

MongoCollection<Document> getCollection(String collectionName);

Source Link

Document

Gets a collection.

Usage

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

License:Apache License

@Override
public void persistNew(DeployExecution deployExecution, PhysicalSchema physicalSchema) {
    MongoDatabase database = mongoClient.getDatabase(physicalSchema.getPhysicalName());
    MongoCollection<Document> auditCollection = database.getCollection(deployExecutionTableName);

    MutableInt mutableInt = nextIdBySchema.get(physicalSchema);
    mutableInt.increment();/*from  www  .j av a  2  s . co m*/
    ((DeployExecutionImpl) deployExecution).setId(mutableInt.longValue());
    Document doc = getDocumentFromDeployExecution(deployExecution, false);
    auditCollection.insertOne(doc);
}

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

License:Apache License

@Override
public void update(DeployExecution deployExecution) {
    MongoDatabase database = mongoClient
            .getDatabase(env.getPhysicalSchema(deployExecution.getSchema()).getPhysicalName());
    MongoCollection<Document> auditCollection = database.getCollection(deployExecutionTableName);

    auditCollection.replaceOne(getChangeFilter(deployExecution),
            getDocumentFromDeployExecution(deployExecution, true));
}

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

License:Apache License

@Override
public ImmutableCollection<DeployExecution> getDeployExecutions(String schema) {
    PhysicalSchema physicalSchema = env.getPhysicalSchema(schema);

    MongoDatabase database = mongoClient.getDatabase(physicalSchema.getPhysicalName());
    MongoCollection<Document> auditCollection = database.getCollection(deployExecutionTableName);

    return iterableToCollection(auditCollection.find()).collect(new Function<Document, DeployExecution>() {
        @Override//from   ww w  .  j a va  2s.co m
        public DeployExecution valueOf(Document doc) {
            MutableList<Document> attrsList = ListAdapter.adapt(doc.get("attrs", List.class));
            MutableList<DeployExecutionAttribute> attrs = attrsList
                    .collect(new Function<Document, DeployExecutionAttribute>() {
                        @Override
                        public DeployExecutionAttribute valueOf(Document object) {
                            return new DeployExecutionAttributeImpl(object.getString(attrNameColName),
                                    object.getString(attrValueColName));
                        }
                    });

            DeployExecutionImpl exec = new DeployExecutionImpl(doc.getString(requesterIdColName),
                    doc.getString(deployExecutionIdColName), doc.getString(dbSchemaColName),
                    doc.getString(toolVersionColName), new Timestamp(doc.getDate(deployTimeColName).getTime()),
                    doc.getBoolean(initCommandColName), doc.getBoolean(rollbackCommandColName),
                    doc.getString(productVersionColName), doc.getString(reasonColName),
                    attrs.toSet().toImmutable());
            exec.setId(doc.getLong(idColName));

            return exec;
        }
    }).toImmutable();
}

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

License:Open Source License

public static void dropCollections(TxDatabase client) throws Exception {

    MongoDatabase db = client.getDatabase();
    for (String colName : new String[] { COL_HOLDING, COL_QUOTE, COL_ACCOUNT, COL_ACCOUNTPROFILE, COL_ORDER }) {
        out.println("drop " + colName);
        MongoCollection<Document> col = db.getCollection(colName);
        if (col != null)
            col.drop();//w w w.  ja  va 2  s.c  om
    }
}

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);//from   ww w  .  j  ava2 s.  c om

    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);
    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  .  jav a 2  s  .co 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.ibm.research.mongotx.lrc.LatestReadCommittedTxDB.java

License:Open Source License

private boolean isSharding() {
    try {/*from w  ww.  jav a  2s .  co m*/
        MongoDatabase configDB = client.getDatabase("config");
        if (configDB == null)
            return false;

        MongoCollection<Document> databasesCol = configDB.getCollection("databases");
        if (databasesCol == null)
            return false;

        Iterator<Document> dbInfoItr = databasesCol.find(new Document(ATTR_ID, db.getName())).iterator();

        if (!dbInfoItr.hasNext())
            return false;

        return (Boolean) dbInfoItr.next().get("partitioned");
    } catch (MongoQueryException ex) {
        return false;
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }
}

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

License:Open Source License

private void initShardKeysIfNecessary() {
    if (!txDB.isSharding)
        return;//from  w  w w .j av  a 2 s .  c o  m

    try {
        MongoDatabase configDB = txDB.client.getDatabase("config");
        if (configDB == null)
            return;

        MongoCollection<Document> collectionsCol = configDB.getCollection("collections");
        if (collectionsCol == null)
            return;

        Iterator<Document> itrShardInfo = collectionsCol.find(
                new Document(ATTR_ID, txDB.db.getName() + "." + baseCol.getNamespace().getCollectionName()))
                .iterator();
        if (!itrShardInfo.hasNext())
            return;

        Document shardKeys = (Document) itrShardInfo.next().get("key");
        if (shardKeys == null)
            return;

        this.shardKeys.addAll(shardKeys.keySet());

    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, "shardkey init error. msg=" + ex.getMessage(), ex);
    }
}

From source file:com.imaginea.mongodb.services.impl.CollectionServiceImpl.java

License:Apache License

/**
 * Creates a collection inside a database in mongo to which user is connected to.
 *
 * @param dbName Name of Database in which to insert a collection
 * @param selectedCollectionName Collection on which the operation is performed
 * @param newCollName Name of Collection to be added/renamed to
 * @param capped Specify if the collection is capped
 * @param size Specify the size of collection
 * @param maxDocs specify maximum no of documents in the collection
 * @return Success if Insertion is successful else throw exception
 * @throws DatabaseException throw super type of UndefinedDatabaseException
 * @throws ValidationException throw super type of
 *         EmptyDatabaseNameException,EmptyCollectionNameException
 * @throws CollectionException throw super type of
 *         DuplicateCollectionException,InsertCollectionException
 *///  w  w w.j  av a 2  s  . c  o m
public String updateCollection(String dbName, String selectedCollectionName, String newCollName, boolean capped,
        long size, int maxDocs, boolean autoIndexId)
        throws DatabaseException, CollectionException, ValidationException {

    if (dbName == null || dbName.equals("")) {
        throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Invalid Database name");
    }

    if (selectedCollectionName == null || newCollName == null) {
        throw new CollectionException(ErrorCodes.COLLECTION_NAME_EMPTY, "Collection name should be provided");
    }
    if (selectedCollectionName.equals("") || newCollName.equals("")) {
        throw new CollectionException(ErrorCodes.COLLECTION_NAME_EMPTY, "Collection name cannot be empty");
    }
    String result = "No updates were specified!";
    try {
        // if (!databaseService.getDbList().contains(dbName)) {
        //   throw new DatabaseException(ErrorCodes.DB_DOES_NOT_EXISTS,
        //       "Db with name [" + dbName + "] doesn't exist.");
        // }

        boolean convertedToCapped = false, convertedToNormal = false, renamed = false;

        MongoDatabase db = mongoInstance.getDatabase(dbName);
        MongoCollection<Document> selectedCollection = db.getCollection(selectedCollectionName);
        CreateCollectionOptions options = new CreateCollectionOptions();
        options.capped(capped);
        if (capped) {
            options.maxDocuments(maxDocs);
            options.autoIndex(autoIndexId);
            options.sizeInBytes(size);
            createCollection(options, selectedCollection, selectedCollectionName, db);
            convertedToCapped = true;
        } else {
            createCollection(options, selectedCollection, selectedCollectionName, db);
            convertedToNormal = true;
        }

        if (!selectedCollectionName.equals(newCollName)) {
            if (getCollList(dbName).contains(newCollName)) {
                throw new CollectionException(ErrorCodes.COLLECTION_ALREADY_EXISTS,
                        "Collection [" + newCollName + "] already exists in Database [" + dbName + "]");
            }
            selectedCollection = db.getCollection(selectedCollectionName);

            MongoNamespace mongoNamespace = new MongoNamespace(dbName + "." + newCollName);

            selectedCollection.renameCollection(mongoNamespace);
            renamed = true;
        }
        if ((convertedToNormal || convertedToCapped) && renamed) {
            result = "Collection [" + selectedCollectionName + "] was successfully updated.";
        } else if (convertedToCapped) {
            result = "Collection [" + selectedCollectionName
                    + "] was successfully converted to capped collection";
        } else if (convertedToNormal) {
            result = "Capped Collection [" + selectedCollectionName
                    + "] was successfully converted to normal collection";
        } else if (renamed) {
            result = "Collection [" + selectedCollectionName + "] was successfully renamed to '" + newCollName
                    + "'";
        }
    } catch (MongoException m) {
        throw new CollectionException(ErrorCodes.COLLECTION_UPDATE_EXCEPTION, m.getMessage());
    }
    return result;
}

From source file:com.imaginea.mongodb.services.impl.CollectionServiceImpl.java

License:Apache License

/**
 * Deletes a collection inside a database in mongo to which user is connected to.
 *
 * @param dbName Name of Database in which to insert a collection
 * @param collectionName Name of Collection to be inserted
 * @return Success if deletion is successful else throw exception
 * @throws DatabaseException throw super type of UndefinedDatabaseException
 * @throws ValidationException throw super type of
 *         EmptyDatabaseNameException,EmptyCollectionNameException
 * @throws CollectionException throw super type of
 *         UndefinedCollectionException,DeleteCollectionException
 *///from w w  w .j a  v a 2 s . c  o m

private void createCollection(CreateCollectionOptions options, MongoCollection<Document> selectedCollection,
        String selectedCollectionName, MongoDatabase db) {
    db.createCollection(selectedCollectionName + "_temp", options);
    MongoCollection<Document> tempCollection = db.getCollection(selectedCollectionName + "_temp");

    MongoCursor<Document> cur = selectedCollection.find().iterator();
    while (cur.hasNext()) {
        Document obj = cur.next();
        tempCollection.insertOne(obj);
    }
    MongoNamespace namespace = selectedCollection.getNamespace();
    selectedCollection.drop();
    tempCollection.renameCollection(namespace);
}