下面列出了com.mongodb.DB#getCollection ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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;
}
/**
* 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;
}
}
/**
* 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();
}
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);
}
private void init(){
// For Annotation
ApplicationContext ctx =
new AnnotationConfigApplicationContext(MongoConfiguration.class);
db = (DB) ctx.getBean("mongoDb");
coll = db.getCollection("plants");
}
/**
* 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;
}
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);
}
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;
}
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);
}
}
}
}
}
/**
* 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();
}
}
@Override
public void setDb(DB db) {
super.setDb(db);
dependencies = new PuppetDependencyCollection(db.getCollection("Puppet.dependencies"));
pongoCollections.add(dependencies);
}
@Override
public void setDb(DB db) {
super.setDb(db);
newVersions = new NewVersionCollection(db.getCollection("newVersions.maven"));
pongoCollections.add(newVersions);
}
@Override
public void setDb(DB db) {
super.setDb(db);
dockerAntipatterns = new DockerAntipatternCollection(db.getCollection("Docker.antipatterns"));
pongoCollections.add(dockerAntipatterns);
}
@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() );
}
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);
}
private DBCollection getCollection() {
DB occasions = mongo.getMongoDB();
return occasions.getCollection("occasions");
}
@Override
public void setDb(DB db) {
super.setDb(db);
smells = new DockerSmellCollection(db.getCollection("Docker.smells"));
pongoCollections.add(smells);
}
@Override
public void setDb(DB db) {
super.setDb(db);
measurements = new MeasurementCollection(db.getCollection(collectionName));
pongoCollections.add(measurements);
}
@Override
public void setDb(DB db) {
super.setDb(db);
newVersions = new NewVersionCollection(db.getCollection("newVersions.puppet"));
pongoCollections.add(newVersions);
}
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;
}