List of usage examples for com.mongodb.client.model CreateCollectionOptions CreateCollectionOptions
CreateCollectionOptions
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 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 *///from ww w . j ava 2 s. c om public String insertCollection(String dbName, 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 (newCollName == null || newCollName.equals("")) { throw new CollectionException(ErrorCodes.COLLECTION_NAME_EMPTY, "Invalid Collection name"); } try { // if (!databaseService.getDbList().contains(dbName)) { // throw new DatabaseException(ErrorCodes.DB_DOES_NOT_EXISTS, // "Db with name [" + dbName + "] doesn't exist."); // } if (getCollList(dbName).contains(newCollName)) { throw new CollectionException(ErrorCodes.COLLECTION_ALREADY_EXISTS, "Collection [" + newCollName + "] already exists in Database [" + dbName + "]"); } // DBObject options = new BasicDBObject(); CreateCollectionOptions options = new CreateCollectionOptions(); options.capped(capped); if (capped) { options.maxDocuments(maxDocs); options.autoIndex(autoIndexId); options.sizeInBytes(size); } mongoInstance.getDatabase(dbName).createCollection(newCollName, options); } catch (MongoException m) { throw new CollectionException(ErrorCodes.COLLECTION_CREATION_EXCEPTION, m.getMessage()); } return "Collection [" + newCollName + "] was successfully added to Database [" + dbName + "]."; }
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 *///from w w w .j a v 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.telefonica.iot.cygnus.backends.mongo.MongoBackendImpl.java
License:Open Source License
/** * Creates a collection for plain MongoDB, given its name, if not exists in the given database. Size-based limits * are set, if possible. Time-based limits are also set, if possible. * @param dbName/*from www . j a va 2s . c o m*/ * @param collectionName * @param collectionsSize * @param maxDocuments * @throws Exception */ @Override public void createCollection(String dbName, String collectionName, long collectionsSize, long maxDocuments, long dataExpiration) throws Exception { MongoDatabase db = getDatabase(dbName); // create the collection, with size-based limits if possible try { if (collectionsSize != 0 && maxDocuments != 0) { CreateCollectionOptions options = new CreateCollectionOptions().capped(true) .sizeInBytes(collectionsSize).maxDocuments(maxDocuments); LOGGER.debug("Creating Mongo collection=" + collectionName + " at database=" + dbName + " with " + "collections_size=" + collectionsSize + " and max_documents=" + maxDocuments + " options"); db.createCollection(collectionName, options); } else { LOGGER.debug("Creating Mongo collection=" + collectionName + " at database=" + dbName); db.createCollection(collectionName); } // if else } 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 // ensure the recvTime index, if possible try { if (dataExpiration != 0) { BasicDBObject keys = new BasicDBObject().append("recvTime", 1); IndexOptions options = new IndexOptions().expireAfter(dataExpiration, TimeUnit.SECONDS); db.getCollection(collectionName).createIndex(keys, options); } // if } catch (Exception e) { throw e; } // try catch }
From source file:io.mandrel.common.mongo.MongoUtils.java
License:Apache License
public static void checkCapped(MongoDatabase database, String collectionName, int size, int maxDocuments) { if (Lists.newArrayList(database.listCollectionNames()).contains(collectionName)) { log.debug("'{}' collection already exists...", collectionName); // Check if already capped Document command = new Document("collStats", collectionName); boolean isCapped = database.runCommand(command, ReadPreference.primary()).getBoolean("capped") .booleanValue();/*from w ww. ja v a 2 s .c o m*/ if (!isCapped) { log.info("'{}' is not capped, converting it...", collectionName); command = new Document("convertToCapped", collectionName).append("size", size).append("max", maxDocuments); database.runCommand(command, ReadPreference.primary()); } else { log.debug("'{}' collection already capped!", collectionName); } } else { database.createCollection(collectionName, new CreateCollectionOptions().capped(true).maxDocuments(maxDocuments).sizeInBytes(size)); } }
From source file:mongodb.QuickTourAdmin.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args/* w w w .j a v a 2s.c o m*/ * takes an optional single argument for the connection string */ public static void main(final String[] args) { MongoClient mongoClient; if (args.length == 0) { // connect to the specified database server mongoClient = new MongoClient("10.9.17.105", 27017); } else { mongoClient = new MongoClient(new MongoClientURI(args[0])); } // get handle to "test" database MongoDatabase database = mongoClient.getDatabase("test"); database.drop(); // get a handle to the "test" collection MongoCollection<Document> collection = database.getCollection("test"); // drop all the data in it collection.drop(); // getting a list of databases for (String name : mongoClient.listDatabaseNames()) { System.out.println(name); } // drop a database mongoClient.getDatabase("databaseToBeDropped").drop(); // create a collection database.createCollection("cappedCollection", new CreateCollectionOptions().capped(true).sizeInBytes(0x100000)); for (String name : database.listCollectionNames()) { System.out.println(name); } // drop a collection: collection.drop(); // create an ascending index on the "i" field // 1 ascending or -1 for descending collection.createIndex(new Document("i", 1)); // list the indexes on the collection for (final Document index : collection.listIndexes()) { System.out.println(index.toJson()); } // create a text index on the "content" field // text indexes to support text search of string content collection.createIndex(new Document("content", "text")); collection.insertOne(new Document("_id", 0).append("content", "textual content")); collection.insertOne(new Document("_id", 1).append("content", "additional content")); collection.insertOne(new Document("_id", 2).append("content", "irrelevant content")); // Find using the text index long matchCount = collection.count(text("textual content -irrelevant")); System.out.println("Text search matches: " + matchCount); // Find using the $language operator Bson textSearch = text("textual content -irrelevant", "english"); matchCount = collection.count(textSearch); System.out.println("Text search matches (english): " + matchCount); // Find the highest scoring match Document projection = new Document("score", new Document("$meta", "textScore")); Document myDoc = collection.find(textSearch).projection(projection).first(); System.out.println("Highest scoring document: " + myDoc.toJson()); // Run a command Document buildInfo = database.runCommand(new Document("buildInfo", 1)); System.out.println(buildInfo); // release resources database.drop(); mongoClient.close(); }
From source file:net.netzgut.integral.mongo.internal.services.MongoServiceImplementation.java
License:Apache License
@Override public void capCollection(MongoDatabase db, String collectionName, long sizeInBytes) { final MongoIterable<String> result = db.listCollectionNames(); final List<String> names = result.into(new ArrayList<>()); if (names.contains(collectionName)) { final Document getStats = new Document("collStats", collectionName); final Document stats = db.runCommand(getStats); Object capped = stats.get("capped"); final boolean isCapped = capped != null && capped.equals(1); if (isCapped == false) { final Document convertToCapped = new Document(); convertToCapped.append("convertToCapped", collectionName); convertToCapped.append("size", sizeInBytes); db.runCommand(convertToCapped); // We need to create the index manually after conversion. // See red warning box: http://docs.mongodb.org/v2.2/reference/command/convertToCapped/#dbcmd.convertToCapped db.getCollection(collectionName).createIndex(new Document("_id", 1)); }//w w w . j av a 2s .c o m } else { db.createCollection(collectionName, new CreateCollectionOptions().capped(true).sizeInBytes(sizeInBytes)); } }
From source file:org.apache.eagle.alert.metadata.impl.MongoMetadataDaoImpl.java
License:Apache License
private MongoCollection<Document> getCollection(String collectionName) { // first check if collection exists, if not then create a new collection with cappedSize if (!isCollectionExists(collectionName)) { CreateCollectionOptions option = new CreateCollectionOptions(); option.capped(true);//from w w w . ja va 2 s . c om option.maxDocuments(cappedMaxDocuments); option.sizeInBytes(cappedMaxSize); db.createCollection(collectionName, option); } return db.getCollection(collectionName); }
From source file:org.bananaforscale.cormac.dao.collection.CollectionDataServiceImpl.java
License:Apache License
/** * Creates a new collection explicitly. Because MongoDB creates a collection * implicitly when the collection is first referenced in a command, this * method is not required for usage of said collection. * * @param databaseName the database/*from www . j av a2 s .c o m*/ * @param collectionName the collection to create * @return the result of the operation * @throws DatasourceException * @throws ExistsException * @throws NotFoundException */ @Override public boolean addCollection(String databaseName, String collectionName) throws DatasourceException, ExistsException, NotFoundException { try { if (!databaseExists(databaseName)) { throw new NotFoundException("The database doesn't exist in the datasource"); } if (collectionExists(databaseName, collectionName)) { throw new ExistsException("The collection already exists in the datasource"); } MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName); CreateCollectionOptions options = new CreateCollectionOptions(); options.capped(false); mongoDatabase.createCollection(collectionName, options); return true; } catch (MongoException ex) { logger.error("An error occured while adding the collection", ex); throw new DatasourceException("An error occured while adding the collection"); } }
From source file:org.eclipse.ditto.services.utils.persistence.mongo.streaming.MongoTimestampPersistence.java
License:Open Source License
private static Source<Success, NotUsed> repeatableCreateCappedCollectionSource(final MongoDatabase database, final String collectionName, final long cappedCollectionSizeInBytes) { final CreateCollectionOptions collectionOptions = new CreateCollectionOptions().capped(true) .sizeInBytes(cappedCollectionSizeInBytes).maxDocuments(1); return Source .lazily(() -> Source.fromPublisher(database.createCollection(collectionName, collectionOptions))) .mapMaterializedValue(whatever -> NotUsed.getInstance()) .withAttributes(Attributes.inputBuffer(1, 1)).recoverWithRetries(1, new PFBuilder<Throwable, Source<Success, NotUsed>>().match(MongoCommandException.class, MongoTimestampPersistence::isCollectionAlreadyExistsError, error -> Source.single(Success.SUCCESS)).build()); }
From source file:org.flywaydb.core.internal.metadatatable.MongoMetaDataTable.java
License:Apache License
/** * Creates the metadata collection./*ww w . j a va 2 s .c om*/ * * @param dbName The database where this metadata collection will be created. */ private void createMetadataCollection(String dbName) { LOG.info("In MongoDB " + dbName + ", creating Metadata collection: " + collectionName); // Database types used in the metadata collection schema. BasicDBObject dbInt = new BasicDBObject("$type", "int"); BasicDBObject dbString = new BasicDBObject("$type", "string"); BasicDBObject dbBool = new BasicDBObject("$type", "bool"); BasicDBObject dbDate = new BasicDBObject("$type", "date"); BasicDBObject dbNull = new BasicDBObject("$type", "null"); BasicDBObject checksumTypeInt = new BasicDBObject(MetaDataDocument.CHECKSUM, dbInt); BasicDBObject checksumTypeNull = new BasicDBObject(MetaDataDocument.CHECKSUM, dbNull); BasicDBObject[] checksumType = { checksumTypeInt, checksumTypeNull }; BasicDBObject versionTypeString = new BasicDBObject(MetaDataDocument.VERSION, dbString); BasicDBObject versionTypeNull = new BasicDBObject(MetaDataDocument.VERSION, dbNull); BasicDBObject[] versionType = { versionTypeString, versionTypeNull }; // Database object for setting a valid mongo schema. BasicDBObject validSchema = new BasicDBObject().append(MetaDataDocument.INSTALLED_RANK, dbInt) .append("$or", versionType).append(MetaDataDocument.DESCRIPTION, dbString) .append(MetaDataDocument.TYPE, dbString).append(MetaDataDocument.SCRIPT, dbString) .append("$or", checksumType).append(MetaDataDocument.INSTALLED_BY, dbString) .append(MetaDataDocument.INSTALLED_ON, dbDate).append(MetaDataDocument.EXECUTION_TIME, dbInt) .append(MetaDataDocument.SUCCESS, dbBool); ValidationOptions validator = new ValidationOptions().validator(validSchema) .validationLevel(ValidationLevel.STRICT); CreateCollectionOptions collectionOptions = new CreateCollectionOptions().validationOptions(validator); Boolean dbExists = MongoDatabaseUtil.exists(client, dbName); if (dbExists) { LOG.debug("Database " + dbName + " already exists. Skipping database creation."); } else { LOG.info("Creating Mongo database " + dbName + " ..."); } mongoDatabase.createCollection(collectionName, collectionOptions); LOG.debug("Metadata collection " + collectionName + " created."); this.metadataCollection = mongoDatabase.getCollection(collectionName, BasicDBObject.class); if (!dbExists) addSchemaMarker(); }