Java Code Examples for com.mongodb.DB#getCollection()

The following examples show how to use com.mongodb.DB#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: MongoNativeExtractor.java    From deep-spark with Apache License 2.0 6 votes vote down vote up
/**
 * Gets shards.
 *
 * @param collection the collection
 * @return the shards
 */
private Map<String, String[]> getShards(DBCollection collection) {
    DB config = collection.getDB().getSisterDB("config");
    DBCollection configShards = config.getCollection("shards");

    DBCursor cursorShards = configShards.find();

    Map<String, String[]> map = new HashMap<>();
    while (cursorShards.hasNext()) {
        DBObject currentShard = cursorShards.next();
        String currentHost = (String) currentShard.get("host");
        int slashIndex = currentHost.indexOf("/");
        if (slashIndex > 0) {
            map.put((String) currentShard.get(MONGO_DEFAULT_ID),
                    currentHost.substring(slashIndex + 1).split(","));
        }
    }
    return map;
}
 
Example 2
Source File: MongoDBUtil.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 * Get the DBCollection.
 * @param databaseName
 * @param namespace
 * @param collection
 * @return
 */
public static final DBCollection getDBCollection(String databaseName,
		String namespace, String collection) {

	DB db = getDB(databaseName, namespace, collection);
	String collectionName = null;
	if ( namespace != null ) {
		collectionName = concat(namespace, DOT, collection);
	} else {
		collectionName = collection;
	}
	if ( db != null ) {
		DBCollection coll = db.getCollection(collectionName);
		return coll;
	} else {
		logger.warn("Failed to find database:{}, namespace:{}, collection:{}", new Object[]{
				databaseName, namespace, collection
		});
		return null;
	}
}
 
Example 3
Source File: MongoDBTestHelper.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
/**
 * Inserts a new object with { key: value } at given server.
 * @return The new document's id
 */
public static String insert(AbstractMongoDBServer entity, String key, Object value) {
    LOG.info("Inserting {}:{} at {}", new Object[]{key, value, entity});
    MongoClient mongoClient = clientForServer(entity);
    try {
        DB db = mongoClient.getDB(TEST_DB);
        DBCollection testCollection = db.getCollection(TEST_COLLECTION);
        BasicDBObject doc = new BasicDBObject(key, value);
        testCollection.insert(doc);
        ObjectId id = (ObjectId) doc.get("_id");
        return id.toString();
    } finally {
        mongoClient.close();
    }
}
 
Example 4
Source File: BuguDao.java    From bugu-mongo with Apache License 2.0 5 votes vote down vote up
private void initCollection(String collectionName){
    Entity entity = clazz.getAnnotation(Entity.class);
    DB db = BuguFramework.getInstance().getConnection(entity.connection()).getDB();
    DBCollection dbColl;
    //if capped
    if(entity.capped() && !db.collectionExists(collectionName)){
        DBObject options = new BasicDBObject("capped", true);
        long capSize = entity.capSize();
        if(capSize != Default.CAP_SIZE){
            options.put("size", capSize);
        }
        long capMax = entity.capMax();
        if(capMax != Default.CAP_MAX){
            options.put("max", capMax);
        }
        dbColl = db.createCollection(collectionName, options);
    }else{
        dbColl = db.getCollection(collectionName);
    }
    setCollection(dbColl);
    
    //for @EnsureIndex
    EnsureIndex ei = clazz.getAnnotation(EnsureIndex.class);
    if(ei != null){
         if(! indexedSet.contains(collectionName)){
            synchronized (this) {
                if(! indexedSet.contains(collectionName)){
                    List<DBIndex> list = IndexUtil.getDBIndex(ei.value());
                    for(DBIndex dbi : list){
                        getCollection().createIndex(dbi.indexKeys, dbi.indexOptions);
                    }
                    indexedSet.add(collectionName);
                }
            }
        }
    }
}
 
Example 5
Source File: MongoWrapper.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public DBCollection openMongoDb() throws UnknownHostException {

    	MongoClientURI dbUri = new MongoClientURI(dbUriStr_+"?socketTimeoutMS=180000");
	    mongoClient_ = new MongoClient(dbUri);

	    DB db = mongoClient_.getDB( dbName_ );
	    DBCollection coll = db.getCollection(collection_);
	    coll.createIndex(new BasicDBObject(index_, 1));  // create index on "i", ascending

	    return coll;

    }
 
Example 6
Source File: UserResource.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get all user profiles.
 *
 * @return All user profiles (excluding private fields like password).
 */
@GET
@Produces("application/json")
public Response getAllUsers() {
  // Validate the JWT. The JWT must be in the 'users' group.
  try {
    validateJWT(new HashSet<String>(Arrays.asList("users")));
  } catch (JWTException jwte) {
    return Response.status(Status.UNAUTHORIZED)
        .type(MediaType.TEXT_PLAIN)
        .entity(jwte.getMessage())
        .build();
  }

  // Get all the users from the database, and add them to an array.
  DB database = mongo.getMongoDB();
  DBCollection dbCollection = database.getCollection(User.DB_COLLECTION_NAME);
  DBCursor cursor = dbCollection.find();
  JsonArrayBuilder userArray = Json.createArrayBuilder();
  while (cursor.hasNext()) {
    // Exclude all private information from the list.
    userArray.add((new User(cursor.next()).getPublicJsonObject()));
  }

  // Return the user list to the caller.
  JsonObjectBuilder responseBuilder = Json.createObjectBuilder().add("users", userArray.build());
  return Response.ok(responseBuilder.build(), MediaType.APPLICATION_JSON).build();
}
 
Example 7
Source File: MetricHistoryManager.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
public void store(Project project, Date date, IHistoricalMetricProvider provider) {
	DB db = platform.getMetricsRepository(project).getDb();
	
	DBCollection collection = db.getCollection(provider.getCollectionName());

	MetricProviderContext context = new MetricProviderContext(platform, OssmeterLoggerFactory.getInstance().makeNewLoggerInstance(provider.getIdentifier()));
	context.setDate(date);
	provider.setMetricProviderContext(context);
	Pongo metric = provider.measure(project);
	DBObject dbObject = metric.getDbObject();
	
	dbObject.put("__date", date.toString());
	dbObject.put("__datetime", date.toJavaDate());
	collection.save(dbObject);
}
 
Example 8
Source File: MongoBenchmark.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public static void testStringUserId(int max, DB db) {
	String collName = "teststringid";
	DBCollection coll = db.getCollection(collName);
	
	//Setup a sharded collection
	BasicDBObject command = new BasicDBObject();
	command.put("shardcollection", collName);
	DBObject key = new BasicDBObject();
	key.put("_id", 1);
	command.put("key", key);
	command.put("unique", true);
	db.command(command);
	
	long startM = System.currentTimeMillis();
	BasicDBObject obj = new BasicDBObject();
	for ( int i=0; i<max; i++ ) {
		obj.put("_id",  "username"+i);
		obj.put("test", "value-"+i);
		coll.save(obj);
	}
	long endM = System.currentTimeMillis();
	
	System.out.println("Insert " + max + " my objectid. time: " + (endM-startM) + " benchmark()");
	
	CommandResult result = db.getStats();
	System.out.println(result);
}
 
Example 9
Source File: ShoppingCartQueryManager.java    From cqrs-sample with MIT License 5 votes vote down vote up
private void init(){
	// For Annotation
	ApplicationContext ctx = 
             new AnnotationConfigApplicationContext(MongoConfiguration.class);
	db = (DB) ctx.getBean("mongoDb");

	coll = db.getCollection("plants");
}
 
Example 10
Source File: MongoNativeExtractor.java    From deep-spark with Apache License 2.0 5 votes vote down vote up
/**
 * Is sharded collection.
 *
 * @param collection the collection
 * @return the boolean
 */
private boolean isShardedCollection(DBCollection collection) {

    DB config = collection.getDB().getMongo().getDB("config");
    DBCollection configCollections = config.getCollection("collections");

    DBObject dbObject = configCollections.findOne(new BasicDBObject(MONGO_DEFAULT_ID, collection.getFullName()));
    return dbObject != null;
}
 
Example 11
Source File: NewPuppetVersions.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void setDb(DB db) {
	super.setDb(db);
	newVersions = new NewVersionCollection(db.getCollection("newVersions.puppet"));
	pongoCollections.add(newVersions);
}
 
Example 12
Source File: RascalMetrics.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void setDb(DB db) {
	super.setDb(db);
	measurements = new MeasurementCollection(db.getCollection(collectionName));
	pongoCollections.add(measurements);
}
 
Example 13
Source File: DockerSmells.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void setDb(DB db) {
	super.setDb(db);
	smells = new DockerSmellCollection(db.getCollection("Docker.smells"));
	pongoCollections.add(smells);
}
 
Example 14
Source File: OccasionResource.java    From sample-acmegifts with Eclipse Public License 1.0 4 votes vote down vote up
private DBCollection getCollection() {
  DB occasions = mongo.getMongoDB();
  return occasions.getCollection("occasions");
}
 
Example 15
Source File: SingleCollectionAllocator.java    From hvdf with Apache License 2.0 4 votes vote down vote up
public SingleCollectionAllocator(PluginConfiguration config){
	
	String prefix = config.get(HVDF.PREFIX, String.class);
	DB db = config.get(HVDF.DB, DB.class);
	this.collection = db.getCollection(prefix);
}
 
Example 16
Source File: MongoQueryTest.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@Test
public void greaterThanEqual() throws Exception {

    UUID appId = emf.lookupApplication( "test-organization/test-app" );
    EntityManager em = emf.getEntityManager( appId );

    Map<String, Object> properties = new LinkedHashMap<String, Object>();
    properties.put( "name", "Kings of Leon" );
    properties.put( "genre", "Southern Rock" );
    properties.put( "founded", 2000 );
    em.create( "greaterthanequal", properties );

    properties = new LinkedHashMap<String, Object>();
    properties.put( "name", "Stone Temple Pilots" );
    properties.put( "genre", "Rock" );
    properties.put( "founded", 1986 );
    em.create( "greaterthanequal", properties );

    properties = new LinkedHashMap<String, Object>();
    properties.put( "name", "Journey" );
    properties.put( "genre", "Classic Rock" );
    properties.put( "founded", 1973 );
    em.create( "greaterthanequal", properties );

    // See http://www.mongodb.org/display/DOCS/Java+Tutorial

    Mongo m = new Mongo( "localhost", 27017 );

    DB db = m.getDB( "test-organization/test-app" );
    db.authenticate( "test", "test".toCharArray() );

    BasicDBObject query = new BasicDBObject();
    query.put( "founded", new BasicDBObject( "$gte", 1973 ) );

    DBCollection coll = db.getCollection( "greaterthanequals" );
    DBCursor cur = coll.find( query );

    assertTrue( cur.hasNext() );

    DBObject result = cur.next();
    assertEquals( "Journey", result.get( "name" ) );
    assertEquals( "Classic Rock", result.get( "genre" ) );

    result = cur.next();
    assertEquals( "Stone Temple Pilots", result.get( "name" ) );
    assertEquals( "Rock", result.get( "genre" ) );

    result = cur.next();
    assertEquals( "Kings of Leon", result.get( "name" ) );
    assertEquals( "Southern Rock", result.get( "genre" ) );

    assertFalse( cur.hasNext() );
}
 
Example 17
Source File: DockerAntipatterns.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void setDb(DB db) {
	super.setDb(db);
	dockerAntipatterns = new DockerAntipatternCollection(db.getCollection("Docker.antipatterns"));
	pongoCollections.add(dockerAntipatterns);
}
 
Example 18
Source File: NewMavenVersions.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void setDb(DB db) {
	super.setDb(db);
	newVersions = new NewVersionCollection(db.getCollection("newVersions.maven"));
	pongoCollections.add(newVersions);
}
 
Example 19
Source File: PuppetDependencies.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void setDb(DB db) {
	super.setDb(db);
	dependencies = new PuppetDependencyCollection(db.getCollection("Puppet.dependencies"));
	pongoCollections.add(dependencies);
}
 
Example 20
Source File: MongoWrapper.java    From xDrip-Experimental with GNU General Public License v3.0 3 votes vote down vote up
public DBCollection openMongoDb() throws UnknownHostException {

    	MongoClientURI dbUri = new MongoClientURI(dbUriStr_+"?socketTimeoutMS=180000");
	    mongoClient_ = new MongoClient(dbUri);

	    DB db = mongoClient_.getDB( dbName_ );
	    DBCollection coll = db.getCollection(collection_);
	    coll.createIndex(new BasicDBObject(index_, 1));  // create index on "i", ascending

	    return coll;

    }