Java Code Examples for com.mongodb.client.MongoDatabase#getCollection()

The following examples show how to use com.mongodb.client.MongoDatabase#getCollection() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MongoDBUtil.java    From sockslib with Apache License 2.0 6 votes vote down vote up
/**
 * Connect MongoDB and call callback, close connection at last.
 *
 * @param collectionName Collection name.
 * @param callback       Callback
 * @param <T>            The type of value which you want to return.
 * @return The value which callback returned.
 */
public <T> T connect(String collectionName, CollectionCallback<T> callback) {
  MongoClient client = null;
  T t = null;
  try {
    client = getConnectedClient();
    MongoDatabase database = client.getDatabase(databaseName);
    MongoCollection<Document> collection = database.getCollection(collectionName);
    t = callback.doInCollection(collection);
  } finally {
    if (client != null) {
      client.close();
    }
  }
  return t;
}
 
Example 2
Source File: MongoCollectionFindAndModify.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings( "rawtypes" )
public cfData execute(cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException {
	MongoDatabase	db	= getMongoDatabase( _session, argStruct );
	
	String collection	= getNamedStringParam(argStruct, "collection", null);
	if ( collection == null )
		throwException(_session, "please specify a collection");
	
	cfData	update	= getNamedParam(argStruct, "update", null );
	if ( update == null )
		throwException(_session, "please specify update");
	
	cfData	query	= getNamedParam(argStruct, "query", null );
	if ( query == null )
		throwException(_session, "please specify query to update");

	try{
		
		MongoCollection<Document> col = db.getCollection(collection);
		FindOneAndUpdateOptions	findOneAndUpdateOptions	= new FindOneAndUpdateOptions();
		
		if ( getNamedParam(argStruct, "fields", null ) != null )
			findOneAndUpdateOptions.projection( getDocument( getNamedParam(argStruct, "fields", null ) ) );

		if ( getNamedParam(argStruct, "sort", null ) != null )
			findOneAndUpdateOptions.sort( getDocument( getNamedParam(argStruct, "sort", null ) ) );

		findOneAndUpdateOptions.upsert( getNamedBooleanParam(argStruct, "upsert", false ) );
		
		if ( getNamedBooleanParam(argStruct, "returnnew", false ) )
			findOneAndUpdateOptions.returnDocument( ReturnDocument.AFTER );
		
		Document qry = getDocument(query);
		long start = System.currentTimeMillis();
		
		Document result = col.findOneAndUpdate( qry, getDocument(update), findOneAndUpdateOptions );
		
		_session.getDebugRecorder().execMongo(col, "findandmodify", qry, System.currentTimeMillis()-start);
		
		return tagUtils.convertToCfData( (Map)result );

	} catch (MongoException me){
		throwException(_session, me.getMessage());
		return null;
	}
}
 
Example 3
Source File: ChangeEntryIndexDaoTest.java    From mongobee with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore("Fongo has not implemented dropIndex for MongoCollection object (issue with mongo driver 3.x)")
public void shouldDropWrongIndex() {
  // init
  MongoClient mongo = mock(MongoClient.class);
  MongoDatabase db = new Fongo(TEST_SERVER).getDatabase(DB_NAME);
  when(mongo.getDatabase(Mockito.anyString())).thenReturn(db);

  MongoCollection<Document> collection = db.getCollection(CHANGELOG_COLLECTION_NAME);
  collection.createIndex(new Document()
      .append(ChangeEntry.KEY_CHANGEID, 1)
      .append(ChangeEntry.KEY_AUTHOR, 1));
  Document index = new Document("name", CHANGEID_AUTHOR_INDEX_NAME);

  // given
  Document createdIndex = findIndex(db, CHANGEID_AUTHOR_INDEX_NAME);
  assertNotNull(createdIndex);
  assertFalse(dao.isUnique(createdIndex));

  // when
  dao.dropIndex(db.getCollection(CHANGELOG_COLLECTION_NAME), index);

  // then
  assertNull(findIndex(db, CHANGEID_AUTHOR_INDEX_NAME));
}
 
Example 4
Source File: MongoBackendImpl.java    From fiware-cygnus with GNU Affero General Public License v3.0 6 votes vote down vote up
private void insertContextDataAggregatedForResoultion(String dbName, String collectionName,
        GregorianCalendar calendar, String entityId, String entityType, String attrName, String attrType,
        double max, double min, double sum, double sum2, int numSamples, Resolution resolution) {
    // Get database and collection
    MongoDatabase db = getDatabase(dbName);
    MongoCollection collection = db.getCollection(collectionName);

    // Build the query
    BasicDBObject query = buildQueryForInsertAggregated(calendar, entityId, entityType, attrName, resolution);

    // Prepopulate if needed
    BasicDBObject insert = buildInsertForPrepopulate(attrType, resolution, true);
    UpdateResult res = collection.updateOne(query, insert, new UpdateOptions().upsert(true));

    if (res.getMatchedCount() == 0) {
        LOGGER.debug("Prepopulating data, database=" + dbName + ", collection=" + collectionName + ", query="
                + query.toString() + ", insert=" + insert.toString());
    } // if

    // Do the update
    BasicDBObject update = buildUpdateForUpdate(attrType, calendar, max, min, sum, sum2, numSamples);
    LOGGER.debug("Updating data, database=" + dbName + ", collection=" + collectionName + ", query="
            + query.toString() + ", update=" + update.toString());
    collection.updateOne(query, update);
}
 
Example 5
Source File: MongoAdminService.java    From cloudfoundry-service-broker with Apache License 2.0 6 votes vote down vote up
public MongoDatabase createDatabase(String databaseName) throws MongoServiceException {
	try {
		addDbOwnerRole(databaseName);
		
		MongoDatabase db = client.getDatabase(databaseName);
		db.createCollection("foo");
		// save into a collection to force DB creation.
		MongoCollection<Document> col = db.getCollection("foo");
		Document document = new Document("foo", "bar");
		
		col.insertOne(document);
		// drop the collection so the db is empty
		// TODO: figure out how to clean the db in a different "transaction" so the create is flushed
		// currently dropping the column is preventing the database from being created. 
		// col.drop();

		return db;
	} catch (MongoException e) {
		// try to clean up and fail
		try {
			deleteDatabase(databaseName);
		} catch (MongoServiceException ignore) {}
		throw handleException(e);
	}
}
 
Example 6
Source File: MongoOperations.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public static MongoCollection mongoCollection(Class<?> entityClass) {
    MongoEntity mongoEntity = entityClass.getAnnotation(MongoEntity.class);
    MongoDatabase database = mongoDatabase(mongoEntity);
    if (mongoEntity != null && !mongoEntity.collection().isEmpty()) {
        return database.getCollection(mongoEntity.collection(), entityClass);
    }
    return database.getCollection(entityClass.getSimpleName(), entityClass);
}
 
Example 7
Source File: Mongo.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
protected void initialiseForRelations() throws ResourceInitializationException {
  final MongoDatabase db = mongoResource.getDB();
  relationCollection = db.getCollection(relationCollectionName);

  relationCollection.createIndex(new Document(EXTERNAL_ID, 1));
  relationCollection.createIndex(new Document(DOC_ID, 1));
  relationCollection.createIndex(new Document(TYPE, 1));
  relationCollection.createIndex(new Document("subType", 1));

  // The value (being a whole sentence) is too large for index see:
  // https://stackoverflow.com/questions/27792706/cannot-create-index-in-mongodb-key-too-large-to-index
  relationCollection.createIndex(new Document(VALUE, TEXT));
}
 
Example 8
Source File: MongoDbPluginIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() {
    MongoDatabase database = mongoClient.getDatabase("testdb");
    MongoCollection<Document> collection = database.getCollection("test");
    Document document = new Document("test1", "test2")
            .append("test3", "test4");
    collection.insertOne(document);
}
 
Example 9
Source File: MongoCompensableLogger.java    From ByteTCC with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void createTransactionsGlobalTxKeyIndexIfNecessary() {
	String databaseName = CommonUtils.getApplication(this.endpoint).replaceAll("\\W", "_");
	MongoDatabase database = this.mongoClient.getDatabase(databaseName);
	MongoCollection<Document> transactions = database.getCollection(CONSTANTS_TB_TRANSACTIONS);
	ListIndexesIterable<Document> transactionIndexList = transactions.listIndexes();
	boolean transactionIndexExists = false;
	MongoCursor<Document> transactionCursor = null;
	try {
		transactionCursor = transactionIndexList.iterator();
		while (transactionIndexExists == false && transactionCursor.hasNext()) {
			Document document = transactionCursor.next();
			Boolean unique = document.getBoolean("unique");
			Document key = (Document) document.get("key");

			boolean globalExists = key.containsKey(CONSTANTS_FD_GLOBAL);
			boolean lengthEquals = key.size() == 1;
			transactionIndexExists = lengthEquals && globalExists;

			if (transactionIndexExists && (unique == null || unique == false)) {
				throw new IllegalStateException();
			}
		}
	} finally {
		IOUtils.closeQuietly(transactionCursor);
	}

	if (transactionIndexExists == false) {
		Document index = new Document(CONSTANTS_FD_GLOBAL, 1);
		transactions.createIndex(index, new IndexOptions().unique(true));
	}
}
 
Example 10
Source File: MongoTemplateRecordConsumer.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
public void doInitialize(UimaContext aContext) throws ResourceInitializationException {
  super.doInitialize(aContext);
  MongoDatabase db = mongoResource.getDB();
  recordsCollection = db.getCollection(recordsCollectionName);
  objectMapper = new ObjectMapper();
  objectMapper.setSerializationInclusion(Include.NON_NULL);
}
 
Example 11
Source File: MongoDBRyaDAOIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteWildcardSubjectWithContext() throws RyaDAOException, MongoException, IOException {
    final MongoDBRyaDAO dao = new MongoDBRyaDAO();
    try {
        dao.setConf(conf);
        dao.init();

        final RyaStatementBuilder builder = new RyaStatementBuilder();
        builder.setPredicate(new RyaIRI("http://temp.com"));
        builder.setSubject(new RyaIRI("http://subject.com"));
        builder.setObject(new RyaIRI("http://object.com"));
        builder.setContext(new RyaIRI("http://context.com"));
        builder.setColumnVisibility(new DocumentVisibility("A&B&C").flatten());
        final RyaStatement statement = builder.build();

        final MongoDatabase db = conf.getMongoClient().getDatabase(conf.get(MongoDBRdfConfiguration.MONGO_DB_NAME));
        final MongoCollection<Document> coll = db.getCollection(conf.getTriplesCollectionName());

        dao.add(statement);
        assertEquals(1, coll.countDocuments());

        final RyaStatementBuilder builder2 = new RyaStatementBuilder();
        builder2.setPredicate(new RyaIRI("http://temp.com"));
        builder2.setObject(new RyaIRI("http://object.com"));
        builder2.setContext(new RyaIRI("http://context3.com"));
        final RyaStatement query = builder2.build();

        dao.delete(query, conf);
        assertEquals(1, coll.countDocuments());
    } finally {
        dao.destroy();
    }
}
 
Example 12
Source File: MongoBackendImpl.java    From fiware-cygnus with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Inserts a new document in the given raw collection within the given database (row-like mode).
 * @param dbName
 * @param collectionName
 * @param aggregation
 * @throws Exception
 */
@Override
public void insertContextDataRaw(String dbName, String collectionName, ArrayList<Document> aggregation)
    throws Exception {
    MongoDatabase db = getDatabase(dbName);
    MongoCollection collection = db.getCollection(collectionName);
    collection.insertMany(aggregation);
}
 
Example 13
Source File: MongoCollectionSave.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public cfData execute( cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException {
	MongoDatabase db = getMongoDatabase( _session, argStruct );

	String collection = getNamedStringParam( argStruct, "collection", null );
	if ( collection == null )
		throwException( _session, "please specify a collection" );

	cfData data = getNamedParam( argStruct, "data", null );
	if ( data == null )
		throwException( _session, "please specify data to save" );

	try {
		Document doc = getDocument( data );
		MongoCollection<Document> col = db.getCollection( collection );
		long start = System.currentTimeMillis();

		if ( doc.containsKey( "_id" ) ) {
			col.updateOne( new Document( "_id", doc.get( "_id" ) ), new Document("$set",doc) );
		} else {
			col.insertOne( doc );
		}

		_session.getDebugRecorder().execMongo( col, "save", doc, System.currentTimeMillis() - start );

		return cfBooleanData.TRUE;

	} catch ( Exception me ) {
		throwException( _session, me.getMessage() );
		return null;
	}
}
 
Example 14
Source File: MongoDocumentStorage.java    From lumongo with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteAllDocuments() {
	GridFSBucket gridFS = createGridFSConnection();
	gridFS.drop();

	MongoDatabase db = mongoClient.getDatabase(database);
	MongoCollection<Document> coll = db.getCollection(rawCollectionName);
	coll.deleteMany(new Document());
}
 
Example 15
Source File: ProfilingWriter.java    From mongodb-slow-operations-profiler with GNU Affero General Public License v3.0 5 votes vote down vote up
private MongoCollection<Document> getProfileCollection(MongoDbAccessor mongo){
    final MongoDatabase db = mongo.getMongoDatabase(serverDto.getDb());
    final MongoCollection<Document> result =  db.getCollection(serverDto.getCollection());

    if(result == null) {
        throw new IllegalArgumentException("Can't continue without profile collection for " + serverDto.getHosts());
    }
    return result;
}
 
Example 16
Source File: MongoDBSourceIT.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private void insertNewDocs(String collectionName) {
  MongoClient mongo = new MongoClient(mongoContainerIp, mongoContainerMappedPort);
  MongoDatabase db = mongo.getDatabase(DATABASE_NAME);

  MongoCollection<Document> collection = db.getCollection(collectionName);
  collection.insertOne(new Document("value", "document 12345"));

  mongo.close();
}
 
Example 17
Source File: AbstractMongoRepositoryTest.java    From edison-microservice with Apache License 2.0 4 votes vote down vote up
public TestRepository(final MongoDatabase mongoDatabase) {
    super(new MongoProperties());
    this.collection = mongoDatabase.getCollection("test");
}
 
Example 18
Source File: MongoCollectionFind.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
public cfData execute(cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException {
	MongoDatabase	db	= getMongoDatabase( _session, argStruct );
	
	String collection	= getNamedStringParam(argStruct, "collection", null);
	if ( collection == null )
		throwException(_session, "please specify a collection");
	
	cfData	query	= getNamedParam(argStruct, "query", null );
	if ( query == null )
		throwException(_session, "please specify query");
	
	int	size			= getNamedIntParam(argStruct, "size", -1 );
	int	skip			= getNamedIntParam(argStruct, "skip", -1 );
	cfData sort		= getNamedParam(argStruct, 		"sort", null );
	cfData fields	= getNamedParam(argStruct, 		"fields", null );
	
	try{
		MongoCollection<Document> col = db.getCollection(collection);

		// Get the initial cursor
		FindIterable<Document>	cursor;
		long start = System.currentTimeMillis();
		Document qry = getDocument(query);
		
		cursor = col.find( qry );
		
		if ( fields != null )
			cursor = cursor.projection( getDocument(fields) );

		// Are we sorting?
		if ( sort != null )
			cursor	= cursor.sort( getDocument(sort) );
		
		// Are we limiting
		if ( skip != -1 )
			cursor	= cursor.skip(skip);
		
		// How many we bringing back
		if ( size != -1 )
			cursor = cursor.limit(size);

		// Now we can run the query
		cfArrayData	results	= cfArrayData.createArray(1);
		
		cursor.forEach( new Block<Document>() {

			@SuppressWarnings( "rawtypes" )
			@Override
			public void apply( final Document st ) {
				try {
					results.addElement( tagUtils.convertToCfData( (Map)st ) );
				} catch ( cfmRunTimeException e ) {}
			}
		} );
		
		_session.getDebugRecorder().execMongo(col, "find", qry, System.currentTimeMillis()-start);
		
		return results;
	} catch (MongoException me){
		throwException(_session, me.getMessage());
		return null;
	}
}
 
Example 19
Source File: MongoCompensableLogger.java    From ByteTCC with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void upsertCompensable(CompensableArchive archive) throws IOException {
	TransactionXid xid = (TransactionXid) archive.getIdentifier();
	byte[] global = xid.getGlobalTransactionId();
	byte[] branch = xid.getBranchQualifier();
	String globalKey = ByteUtils.byteArrayToString(global);
	String branchKey = ByteUtils.byteArrayToString(branch);
	CompensableInvocation invocation = archive.getCompensable();
	String beanId = (String) invocation.getIdentifier();

	Method method = invocation.getMethod();
	Object[] args = invocation.getArgs();

	String methodDesc = SerializeUtils.serializeMethod(invocation.getMethod());
	byte[] argsByteArray = SerializeUtils.serializeObject(args);
	String argsValue = ByteUtils.byteArrayToString(argsByteArray);

	String application = CommonUtils.getApplication(this.endpoint);

	Document compensable = new Document();
	compensable.append(CONSTANTS_FD_GLOBAL, globalKey);
	compensable.append(CONSTANTS_FD_BRANCH, branchKey);

	compensable.append("transaction_key", archive.getTransactionResourceKey());
	compensable.append("compensable_key", archive.getCompensableResourceKey());

	Xid transactionXid = archive.getTransactionXid();
	Xid compensableXid = archive.getCompensableXid();

	compensable.append("transaction_xid", String.valueOf(transactionXid));
	compensable.append("compensable_xid", String.valueOf(compensableXid));

	compensable.append("coordinator", archive.isCoordinator());
	compensable.append("tried", archive.isTried());
	compensable.append("confirmed", archive.isConfirmed());
	compensable.append("cancelled", archive.isCancelled());

	compensable.append("serviceId", beanId);
	compensable.append("simplified", invocation.isSimplified());
	compensable.append("confirmable_key", invocation.getConfirmableKey());
	compensable.append("cancellable_key", invocation.getCancellableKey());
	compensable.append("args", argsValue);
	compensable.append("interface", method.getDeclaringClass().getName());
	compensable.append("method", methodDesc);

	String databaseName = application.replaceAll("\\W", "_");
	MongoDatabase mdb = this.mongoClient.getDatabase(databaseName);
	MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_TRANSACTIONS);

	Document compensables = new Document();
	compensables.append(String.format("compensables.%s", branchKey), compensable);

	Document document = new Document();
	document.append("$set", compensables);

	UpdateResult result = collection.updateOne(Filters.eq(CONSTANTS_FD_GLOBAL, globalKey), document);
	if (result.getMatchedCount() != 1) {
		throw new IllegalStateException(
				String.format("Error occurred while creating/updating compensable(matched= %s, modified= %s).",
						result.getMatchedCount(), result.getModifiedCount()));
	}
}
 
Example 20
Source File: GroupStore.java    From EDDI with Apache License 2.0 4 votes vote down vote up
@Inject
public GroupStore(MongoDatabase database, IDocumentBuilder documentBuilder) {
    collection = database.getCollection(COLLECTION_GROUPS);
    this.documentBuilder = documentBuilder;
}