本文整理汇总了Java中com.mongodb.DB类的典型用法代码示例。如果您正苦于以下问题:Java DB类的具体用法?Java DB怎么用?Java DB使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DB类属于com.mongodb包,在下文中一共展示了DB类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: generateFile
import com.mongodb.DB; //导入依赖的package包/类
public void generateFile(String filename) {
DB db = MongoHelper.mongoMerchantDB();
DBCollection col = db.getCollection(COLLECTION_SYNONYMS);
DBCursor cursor = col.find();
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename, true)))) {
while (cursor.hasNext()) {
DBObject doc = cursor.next();
String word = doc.get(FIELD_KEY_WORLD) != null ? doc.get(FIELD_KEY_WORLD).toString() : null;
String synonyms = doc.get(FIELD_KEY_WORLD) != null
? StringUtils.join((BasicDBList) doc.get(FIELD_KEY_SYNONYMS), ",") : null;
if (word != null && synonyms != null) {
out.println(createLine(word, synonyms));
}
}
} catch (IOException e) {
throw new RuntimeException("IOException: Current db cursor with id: " + cursor.curr().get("_id"), e);
}
}
示例2: addUsers
import com.mongodb.DB; //导入依赖的package包/类
@ChangeSet(order = "01",
author = "developer",
id = "01-addUsers")
public void addUsers(final DB db) {
final DBCollection userCollection = db.getCollection(User.COLLECTION_NAME);
userCollection.insert(BasicDBObjectBuilder
.start()
.add(FIELD_NAME_ID, new ObjectId("590f86d92449343841cc2c3f"))
.add(User.FIELD_NAME_FIRST_NAME, "User")
.add(User.FIELD_NAME_LAST_NAME, "One")
.add(User.FIELD_NAME_EMAIL, "[email protected]")
.get());
userCollection.insert(BasicDBObjectBuilder
.start()
.add(FIELD_NAME_ID, new ObjectId("590f86d92449343841cc2c40"))
.add(User.FIELD_NAME_FIRST_NAME, "User")
.add(User.FIELD_NAME_LAST_NAME, "Two")
.add(User.FIELD_NAME_EMAIL, "[email protected]")
.get());
}
示例3: createDatabase
import com.mongodb.DB; //导入依赖的package包/类
public DB createDatabase(String databaseName) throws MongoServiceException {
try {
DB db = client.getDB(databaseName);
// save into a collection to force DB creation.
DBCollection col = db.createCollection("foo", null);
BasicDBObject obj = new BasicDBObject();
obj.put("foo", "bar");
col.insert(obj);
// drop the collection so the db is empty
// col.drop();
return db;
} catch (MongoException e) {
// try to clean up and fail
try {
deleteDatabase(databaseName);
} catch (MongoServiceException ignore) {}
throw handleException(e);
}
}
示例4: createServiceInstance
import com.mongodb.DB; //导入依赖的package包/类
@Override
public CreateServiceInstanceResponse createServiceInstance(CreateServiceInstanceRequest request) {
// TODO MongoDB dashboard
ServiceInstance instance = repository.findOne(request.getServiceInstanceId());
if (instance != null) {
throw new ServiceInstanceExistsException(request.getServiceInstanceId(), request.getServiceDefinitionId());
}
instance = new ServiceInstance(request);
if (mongo.databaseExists(instance.getServiceInstanceId())) {
// ensure the instance is empty
mongo.deleteDatabase(instance.getServiceInstanceId());
}
DB db = mongo.createDatabase(instance.getServiceInstanceId());
if (db == null) {
throw new ServiceBrokerException("Failed to create new DB instance: " + instance.getServiceInstanceId());
}
repository.save(instance);
return new CreateServiceInstanceResponse();
}
示例5: addSocialUserConnection
import com.mongodb.DB; //导入依赖的package包/类
@ChangeSet(order = "03", author = "initiator", id = "03-addSocialUserConnection")
public void addSocialUserConnection(DB db) {
DBCollection socialUserConnectionCollection = db.getCollection("jhi_social_user_connection");
socialUserConnectionCollection.createIndex(BasicDBObjectBuilder
.start("user_id", 1)
.add("provider_id", 1)
.add("provider_user_id", 1)
.get(),
"user-prov-provusr-idx", true);
}
示例6: calcularLocalizaciones
import com.mongodb.DB; //导入依赖的package包/类
/**
* Map reduce.
*
* @param mongoOperation
* the mongo operation
* @param a
* the a
* @param b
* the b
* @param c
* the c
* @param d
* the d
* @throws UnknownHostException
*/
static void calcularLocalizaciones() throws UnknownHostException {
String map = "function () { emit(this.localizacion, {count: 1}); }";
String reduce = " function(key, values) { var result = 0; values.forEach(function(value){ result++ }); "
+ "return result; }";
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("craulerdb");
DBCollection ofertas = db.getCollection("ofertas");
MapReduceCommand cmd = new MapReduceCommand(ofertas, map, reduce, null, MapReduceCommand.OutputType.INLINE,
null);
MapReduceOutput out = ofertas.mapReduce(cmd);
for (DBObject o : out.results()) {
System.out.println(o.toString());
}
}
示例7: initialize
import com.mongodb.DB; //导入依赖的package包/类
@Override
public void initialize(UimaContext aContext) throws ResourceInitializationException {
super.initialize(aContext);
String mongoServer = (String) aContext.getConfigParameterValue(PARAM_MONGO_SERVER);
int mongoPort = (Integer) aContext.getConfigParameterValue(PARAM_MONGO_PORT);
String mongoDbName = (String) aContext.getConfigParameterValue(PARAM_MONGO_DB_NAME);
try {
mongoClient = new MongoClient(mongoServer, mongoPort);
} catch (UnknownHostException e) {
throw new ResourceInitializationException(e);
}
DB db = mongoClient.getDB(mongoDbName);
gridFS = new GridFS(db);
}
示例8: getDB
import com.mongodb.DB; //导入依赖的package包/类
public DB getDB(String database, String username, String password) {
if(log.isDebugEnabled()) {
log.debug("username: " + username+", password: " + password+", database: " + database);
}
DB db = mongo.getDB(database);
boolean authenticated = db.isAuthenticated();
if(!authenticated) {
if(username != null && password != null && username.length() > 0 && password.length() > 0) {
authenticated = db.authenticate(username, password.toCharArray());
}
}
if(log.isDebugEnabled()) {
log.debug("authenticated: " + authenticated);
}
return db;
}
示例9: evaluate
import com.mongodb.DB; //导入依赖的package包/类
/**
* Evaluate a script on the database
*
* @param db
* database connection to use
* @param script
* script to evaluate on the database
* @return result of evaluation on the database
* @throws Exception
* when evaluation on the database fails
*/
public Object evaluate(DB db, String script)
throws Exception {
if(log.isDebugEnabled()) {
log.debug("database: " + db.getName()+", script: " + script);
}
db.requestStart();
try {
db.requestEnsureConnection();
Object result = db.eval(script);
if(log.isDebugEnabled()) {
log.debug("Result : " + result);
}
return result;
} finally {
db.requestDone();
}
}
示例10: main
import com.mongodb.DB; //导入依赖的package包/类
public static void main(String[] args) throws IOException {
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("mydb");
DBCollection coll = db.getCollection("questionsCollection");
mongoClient.setWriteConcern(WriteConcern.JOURNALED);
GIFTParser p = new GIFTParser();
BasicDBObject doc = null;
for (Question q : p.parserGIFT("Data/questionsGIFT")) {
doc = new BasicDBObject("category", q.getCategory())
.append("question", q.getText())
.append("correctanswer", q.getCorrectAnswer())
.append("wrongAnswers",q.getWrongAnswers());
coll.insert(doc);
}
DBCursor cursor = coll.find();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
}
示例11: getFactoryInstance
import com.mongodb.DB; //导入依赖的package包/类
@Override
public Repository getFactoryInstance() throws UnknownHostException {
String[] hostArray = this.getHost().split(",");
List<String> hostList = Arrays.asList(hostArray);
List<ServerAddress> serverList = new ArrayList<ServerAddress>();
for( String hostURL : hostList){
ServerAddress sa = new ServerAddress(hostURL);
serverList.add(sa);
}
MongoClient mc = new MongoClient(serverList);
DB db = mc.getDB("gravity");
DocumentNodeStore ns = new DocumentMK.Builder().
setMongoDB(db).getNodeStore();
return new Jcr(new Oak(ns))
.with(new RepositoryIndexInitializer())
.withAsyncIndexing()
.createRepository();
}
示例12: run
import com.mongodb.DB; //导入依赖的package包/类
@Override
public void run(LogWriterConfiguration configuration,
Environment environment) throws UnknownHostException, NoDBNameException {
final MongoClient mongoClient = configuration.getMongoFactory().buildClient(environment);
final DB db = configuration.getMongoFactory().buildDB(environment);
//Register health checks
environment.healthChecks().register("mongo",new MongoHealthCheck(mongoClient));
final LogWriterResource resource = new LogWriterResource(
configuration.getTemplate(),
configuration.getDefaultName(),
db
);
environment.jersey().register(resource);
final LogWriterHealthCheck healthCheck =
new LogWriterHealthCheck(configuration.getTemplate());
environment.healthChecks().register("logwriter", healthCheck);
environment.jersey().register(resource);
}
示例13: setPinStateOfBuild
import com.mongodb.DB; //导入依赖的package包/类
private void setPinStateOfBuild(final String product,
final String version,
final String build,
final boolean state) {
final DB db = this.client.getDB("bdd");
final DBCollection collection = db.getCollection("summary");
final BasicDBObject query = new BasicDBObject("_id",product+"/"+version);
final BasicDBObject toBePinned = new BasicDBObject("pinned",build);
final String method;
if (state) {
method = "$addToSet";
} else {
method = "$pull";
}
collection.update(query, new BasicDBObject(method,toBePinned));
}
示例14: connection
import com.mongodb.DB; //导入依赖的package包/类
public static void connection() {
try {
DB db = (new MongoClient("localhost", 27017)).getDB("Questions");
DBCollection coll = db.getCollection("Questions");
BasicDBObject query = new BasicDBObject();
query.put("id", 1001);
DBCursor cursor = coll.find(query);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
} catch (MongoException e) {
e.printStackTrace();
}
}
示例15: testShellDirect
import com.mongodb.DB; //导入依赖的package包/类
@Test
public void testShellDirect() throws Exception {
Command cmd = this.utility.parseCommand("SELECT * FROM Customers");
MongoDBConnection connection = Mockito.mock(MongoDBConnection.class);
ExecutionContext context = Mockito.mock(ExecutionContext.class);
DBCollection dbCollection = Mockito.mock(DBCollection.class);
DB db = Mockito.mock(DB.class);
Mockito.stub(db.getCollection("MyTable")).toReturn(dbCollection);
Mockito.stub(db.collectionExists(Mockito.anyString())).toReturn(true);
Mockito.stub(connection.getDatabase()).toReturn(db);
Argument arg = new Argument(Direction.IN, null, String.class, null);
arg.setArgumentValue(new Literal("$ShellCmd;MyTable;remove;{ qty: { $gt: 20 }}", String.class));
ResultSetExecution execution = this.translator.createDirectExecution(Arrays.asList(arg), cmd, context, this.utility.createRuntimeMetadata(), connection);
execution.execute();
Mockito.verify(dbCollection).remove(QueryBuilder.start("qty").greaterThan(20).get());
}