com.mongodb.DB#getCollection ( )源码实例Demo

下面列出了com.mongodb.DB#getCollection ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: deep-spark   文件: MongoNativeExtractor.java
/**
 * 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;
}
 
源代码2 项目: gameserver   文件: MongoDBUtil.java
/**
 * 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;
	}
}
 
源代码3 项目: sample-acmegifts   文件: UserResource.java
/**
 * 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();
}
 
源代码4 项目: gameserver   文件: MongoBenchmark.java
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);
}
 
源代码5 项目: cqrs-sample   文件: ShoppingCartQueryManager.java
private void init(){
	// For Annotation
	ApplicationContext ctx = 
             new AnnotationConfigApplicationContext(MongoConfiguration.class);
	db = (DB) ctx.getBean("mongoDb");

	coll = db.getCollection("plants");
}
 
源代码6 项目: deep-spark   文件: MongoNativeExtractor.java
/**
 * 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;
}
 
源代码7 项目: scava   文件: MetricHistoryManager.java
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);
}
 
源代码8 项目: xDrip-plus   文件: MongoWrapper.java
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;

    }
 
源代码9 项目: bugu-mongo   文件: BuguDao.java
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);
                }
            }
        }
    }
}
 
源代码10 项目: brooklyn-library   文件: MongoDBTestHelper.java
/**
 * 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();
    }
}
 
源代码11 项目: scava   文件: PuppetDependencies.java
@Override
public void setDb(DB db) {
	super.setDb(db);
	dependencies = new PuppetDependencyCollection(db.getCollection("Puppet.dependencies"));
	pongoCollections.add(dependencies);
}
 
源代码12 项目: scava   文件: NewMavenVersions.java
@Override
public void setDb(DB db) {
	super.setDb(db);
	newVersions = new NewVersionCollection(db.getCollection("newVersions.maven"));
	pongoCollections.add(newVersions);
}
 
源代码13 项目: scava   文件: DockerAntipatterns.java
@Override
public void setDb(DB db) {
	super.setDb(db);
	dockerAntipatterns = new DockerAntipatternCollection(db.getCollection("Docker.antipatterns"));
	pongoCollections.add(dockerAntipatterns);
}
 
源代码14 项目: usergrid   文件: MongoQueryTest.java
@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() );
}
 
源代码15 项目: hvdf   文件: SingleCollectionAllocator.java
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);
}
 
源代码16 项目: sample-acmegifts   文件: OccasionResource.java
private DBCollection getCollection() {
  DB occasions = mongo.getMongoDB();
  return occasions.getCollection("occasions");
}
 
源代码17 项目: scava   文件: DockerSmells.java
@Override
public void setDb(DB db) {
	super.setDb(db);
	smells = new DockerSmellCollection(db.getCollection("Docker.smells"));
	pongoCollections.add(smells);
}
 
源代码18 项目: scava   文件: RascalMetrics.java
@Override
public void setDb(DB db) {
	super.setDb(db);
	measurements = new MeasurementCollection(db.getCollection(collectionName));
	pongoCollections.add(measurements);
}
 
源代码19 项目: scava   文件: NewPuppetVersions.java
@Override
public void setDb(DB db) {
	super.setDb(db);
	newVersions = new NewVersionCollection(db.getCollection("newVersions.puppet"));
	pongoCollections.add(newVersions);
}
 
源代码20 项目: xDrip-Experimental   文件: MongoWrapper.java
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;

    }