當前位置: 首頁>>代碼示例>>Java>>正文


Java MongoDatabase.getCollection方法代碼示例

本文整理匯總了Java中com.mongodb.client.MongoDatabase.getCollection方法的典型用法代碼示例。如果您正苦於以下問題:Java MongoDatabase.getCollection方法的具體用法?Java MongoDatabase.getCollection怎麽用?Java MongoDatabase.getCollection使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.mongodb.client.MongoDatabase的用法示例。


在下文中一共展示了MongoDatabase.getCollection方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: updateDocumentWithCurrentDate

import com.mongodb.client.MongoDatabase; //導入方法依賴的package包/類
/**
 * This method update document with lastmodified properties 
 */
@Override
public void updateDocumentWithCurrentDate() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    Bson filter = null;
    Bson query = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        filter = eq("name", "Sundar");
        query = combine(set("age", 23), set("gender", "Male"),
                currentDate("lastModified"));
        UpdateResult result = collection.updateOne(filter, query);
        log.info("Update with date Status : " + result.wasAcknowledged());
        log.info("No of Record Modified : " + result.getModifiedCount());
    } catch (MongoException e) {
        log.error("Exception occurred while update Many Document with Date : " + e, e);
    }
}
 
開發者ID:sundarcse1216,項目名稱:mongodb-crud,代碼行數:23,代碼來源:UpdateDocumentsImpl.java

示例2: insertReport

import com.mongodb.client.MongoDatabase; //導入方法依賴的package包/類
/**
 * Inserts a new report to the DB
 * 
 * @param report contains all data for insertion
 */
public static void insertReport(Report report) {
    Document newDocument = new Document();
    newDocument.append("priority", report.getPriority())
            .append("comment", report.getComment())
            .append("resolved", report.isResolved())
            .append("city_item_id", report.getCityItemId());

    if (report.getReportDate() != null) {
        newDocument.append("report_date", report.getReportDate().getTime());
    }
    if (report.getResolveDate() != null) {
        newDocument.append("resolve_date", report.getResolveDate().getTime());
    }

    MongoDatabase db = Configurator.INSTANCE.getDatabase();
    MongoCollection collection = db.getCollection(COLLECTION);
    collection.insertOne(newDocument); //TODO check if succeeds
}
 
開發者ID:Labas-Vakaras,項目名稱:Smart_City,代碼行數:24,代碼來源:ReportDAO.java

示例3: successfulInputOfComment

import com.mongodb.client.MongoDatabase; //導入方法依賴的package包/類
@Test
public void successfulInputOfComment() throws IOException {
    String json = "{ plantId: \"58d1c36efb0cac4e15afd278\", comment : \"Here is our comment for this test\" }";

    assertTrue(plantController.addComment(json, "second uploadId"));

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection<Document> plants = db.getCollection("plants");

    Document filterDoc = new Document();

    filterDoc.append("_id", new ObjectId("58d1c36efb0cac4e15afd278"));
    filterDoc.append("uploadID", "second uploadId");

    Iterator<Document> iter = plants.find(filterDoc).iterator();

    Document plant = iter.next();
    List<Document> plantComments = (List<Document>) ((Document) plant.get("metadata")).get("comments");
    long comments = plantComments.size();

    assertEquals(1, comments);
    assertEquals("Here is our comment for this test", plantComments.get(0).getString("comment"));
    assertNotNull(plantComments.get(0).getObjectId("_id"));
  }
 
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-4-dorfner-v2,代碼行數:26,代碼來源:TestPlantComment.java

示例4: AddFlowerRatingReturnsTrueWithValidJsonInput

import com.mongodb.client.MongoDatabase; //導入方法依賴的package包/類
@Test
public void AddFlowerRatingReturnsTrueWithValidJsonInput() throws IOException{

    String json = "{like: true, id: \"58d1c36efb0cac4e15afd202\"}";

    assertTrue(plantController.addFlowerRating(json, "first uploadId") instanceof ObjectId);

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection plants = db.getCollection("plants");

    FindIterable doc = plants.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd202")));
    Iterator iterator = doc.iterator();
    Document result = (Document) iterator.next();

    List<Document> ratings = (List<Document>) ((Document) result.get("metadata")).get("ratings");
    assertEquals(1, ratings.size());

    Document rating = ratings.get(0);
    assertTrue(rating.getBoolean("like"));
    assertTrue(rating.get("id") instanceof ObjectId);
}
 
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-4-dorfner-v2,代碼行數:23,代碼來源:FlowerRating.java

示例5: insertSingleDocument

import com.mongodb.client.MongoDatabase; //導入方法依賴的package包/類
/**
 * This method insert the single document
 */
@Override
public void insertSingleDocument() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());

        Document canvas = new Document("item", "canvas").append("qty", 100)
                .append("tags", singletonList("cotton"));

        Document size = new Document("h", 28).append("w", 35.5).append(
                "uom", "cm");

        canvas.append("size", size);
        collection.insertOne(canvas);
        log.info("Single Document Insert Successfully...");
    } catch (MongoException | ClassCastException e) {
        log.error("Exception occurred while insert **Single Document** : " + e, e);
    }
}
 
開發者ID:sundarcse1216,項目名稱:mongodb-crud,代碼行數:25,代碼來源:InsertDocumentsImpl.java

示例6: AddFlowerRatingReturnsTrueWithValidInput

import com.mongodb.client.MongoDatabase; //導入方法依賴的package包/類
@Test
public void AddFlowerRatingReturnsTrueWithValidInput() throws IOException{
    assertTrue(plantController.addFlowerRating("58d1c36efb0cac4e15afd202", true, "first uploadId") instanceof ObjectId);

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection plants = db.getCollection("plants");

    FindIterable doc = plants.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd202")));
    Iterator iterator = doc.iterator();
    Document result = (Document) iterator.next();

    List<Document> ratings = (List<Document>) ((Document) result.get("metadata")).get("ratings");
    assertEquals(1, ratings.size());

    Document rating = ratings.get(0);
    assertTrue(rating.getBoolean("like"));
    assertTrue(rating.get("id") instanceof ObjectId);
}
 
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-4-dorfner-v2,代碼行數:20,代碼來源:FlowerRating.java

示例7: saveEntry

import com.mongodb.client.MongoDatabase; //導入方法依賴的package包/類
/**
 * Saves an entry to file
 * @param entry
 * @param dbName usually scrapig
 * @return true if success
 */
public static boolean saveEntry(DBEntry entry, String dbName){

    if(entry == null || !entry.isValid())
        return false;

    Logger log = Logger.getLogger(DAO.class);

    MongoDatabase db = MongoDB.INSTANCE.getDatabase(dbName);

    String collectionName = getCollectionName(entry);


    MongoCollection collection = db.getCollection(collectionName,BasicDBObject.class);

    try {
        collection.insertOne(entry);
        return true;
    }
    catch (MongoWriteException ex){
        if (ex.getCode() != 11000) // Ignore errors about duplicates
            log.error(ex.getError().getMessage());
        return false;
    }

}
 
開發者ID:gidim,項目名稱:Babler,代碼行數:32,代碼來源:DAO.java

示例8: connect

import com.mongodb.client.MongoDatabase; //導入方法依賴的package包/類
private static void connect(String URI){
    //Change MongoDB's logger settings
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    rootLogger = loggerContext.getLogger("org.mongodb.driver");
    rootLogger.setLevel(Level.INFO);

    //Setup Connection
    MongoClientURI connectionString = new MongoClientURI(URI);
    MongoClient mongoClient = new MongoClient(connectionString);
    MongoDatabase database = mongoClient.getDatabase("media_information_service_db");
    collection = database.getCollection("messages");

}
 
開發者ID:LithiumSR,項目名稱:media_information_service,代碼行數:14,代碼來源:MongoDBInterface.java

示例9: populateDatabase

import com.mongodb.client.MongoDatabase; //導入方法依賴的package包/類
public void populateDatabase(String[][] cellValues, String uploadId){
    MongoClient mongoClient = new MongoClient();
    MongoDatabase test = mongoClient.getDatabase(databaseName);
    MongoCollection plants = test.getCollection("plants");

    String[] keys = getKeys(cellValues);

    for (int i = 4; i < cellValues.length; i++){
        Document doc = new Document();
        for(int j = 0; j < cellValues[i].length; j++){
            doc.append(keys[j], cellValues[i][j]);
        }

        if(doc.get("gardenLocation").equals(""))
            continue;

        // Initialize the empty metadata
        Document metadataDoc = new Document();
        metadataDoc.append("pageViews", 0);
        metadataDoc.append("visits", new BsonArray());
        metadataDoc.append("ratings", new BsonArray());

        doc.append("metadata", metadataDoc);
        doc.append("uploadId", uploadId);

        plants.insertOne(doc);
    }




    setLiveUploadId(uploadId);
}
 
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-3-sixguysburgers-fries,代碼行數:34,代碼來源:ExcelParser.java

示例10: initialization

import com.mongodb.client.MongoDatabase; //導入方法依賴的package包/類
@PostConstruct
public void initialization() {
    MongoDatabase database = ConnectionManager.getConnectionManager().getDB();
    flight = database.getCollection("flight");
    flightSegment = database.getCollection("flightSegment");
    airportCodeMapping = database.getCollection("airportCodeMapping");
}
 
開發者ID:ibmruntimes,項目名稱:acmeair-modular,代碼行數:8,代碼來源:FlightServiceImpl.java

示例11: getData

import com.mongodb.client.MongoDatabase; //導入方法依賴的package包/類
/**
 * This method retrieve document(s) based on parameters
 * @param query - query have to execute
 * @param operator - this is for debug purpose
 */
private void getData(Bson query, String operator) {
    MongoDatabase db = null;
    MongoCollection collection = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        FindIterable<Document> list = collection.find(query);
        for (Document doc : list) {
            log.info(doc.getString("name"));
        }
    } catch (MongoException e) {
        log.error("exception occurred while getting Document using " + operator + " : " + e, e);
    }
}
 
開發者ID:sundarcse1216,項目名稱:mongodb-crud,代碼行數:20,代碼來源:QueryDocumentsImpl.java

示例12: id

import com.mongodb.client.MongoDatabase; //導入方法依賴的package包/類
@Then("^Lead with id (\\d+) has field ([\\w_\\.]+) in the database$")
public void Lead_with_id_has_field_in_the_database(int leadId, String fieldName) {
    MongoDatabase database = mongoClientData.getDatabase("local");
    MongoCollection<Document> collection = database.getCollection("leads");
    long count = collection.count(parse("{$and: [{_id: {$eq: \"" + leadId + "\"}}, {\"" + fieldName + "\": {$exists: true}}]}"));
    assertEquals(1, count);
}
 
開發者ID:intellead,項目名稱:intellead-integration-tests,代碼行數:8,代碼來源:Steps.java

示例13: testPushUpdate

import com.mongodb.client.MongoDatabase; //導入方法依賴的package包/類
@Test
public void testPushUpdate() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(new UpdateMongo());
    addMongoService(runner);
    runner.setProperty(MongoProps.DATABASE, MONGO_DATABASE_NAME);
    runner.setProperty(MongoProps.COLLECTION, "insert_test");
    runner.setProperty(MongoProps.UPDATE_QUERY_KEYS, "d.id");
    runner.setProperty(MongoProps.UPDATE_KEYS, "d.media");
    runner.setProperty(MongoProps.UPDATE_OPERATOR, "$addToSet");

    String contents = FileUtils.readFileToString(Paths.get("src/test/resources/update_payload.json").toFile());

    runner.enqueue(contents.getBytes());
    runner.run();

    runner.assertTransferCount(AbstractMongoProcessor.REL_FAILURE, 0);
    runner.assertTransferCount(AbstractMongoProcessor.REL_SUCCESS, 1);

    // Verify whether the update was made
    MongoClient client = mongo.getMongoClient();
    MongoDatabase db = client.getDatabase(MONGO_DATABASE_NAME);
    if (db != null) {
        MongoCollection<Document> collection = db.getCollection("insert_test");
        Document query = buildQuery("d.id", (JsonObject) JSON_PROVIDER.parse(contents));
        assertEquals(1, collection.count(query.append("d.media", new Document("$exists", true))));
    }
}
 
開發者ID:Asymmetrik,項目名稱:nifi-nars,代碼行數:28,代碼來源:UpdateMongoIT.java

示例14: testSetUpdate

import com.mongodb.client.MongoDatabase; //導入方法依賴的package包/類
@Test
public void testSetUpdate() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(new UpdateMongo());
    addMongoService(runner);
    runner.setProperty(MongoProps.DATABASE, MONGO_DATABASE_NAME);
    runner.setProperty(MongoProps.COLLECTION, "insert_test");
    runner.setProperty(MongoProps.UPDATE_QUERY_KEYS, "d.id");
    runner.setProperty(MongoProps.UPDATE_KEYS, "d.s");
    runner.setProperty(MongoProps.UPDATE_OPERATOR, "$set");

    String contents = FileUtils.readFileToString(Paths.get("src/test/resources/update_payload.json").toFile());

    runner.enqueue(contents.getBytes());
    runner.run();

    runner.assertTransferCount(AbstractMongoProcessor.REL_FAILURE, 0);
    runner.assertTransferCount(AbstractMongoProcessor.REL_SUCCESS, 1);

    // Verify whether the update was made
    MongoClient client = mongo.getMongoClient();
    MongoDatabase db = client.getDatabase(MONGO_DATABASE_NAME);
    if (db != null) {
        MongoCollection<Document> collection = db.getCollection("insert_test");
        Document query = buildQuery("d.id", (JsonObject) JSON_PROVIDER.parse(contents));
        assertEquals(collection.count(query.append("d.s", new Document("$eq", "xyz"))), 1);
    }
}
 
開發者ID:Asymmetrik,項目名稱:nifi-nars,代碼行數:28,代碼來源:UpdateMongoIT.java

示例15: process

import com.mongodb.client.MongoDatabase; //導入方法依賴的package包/類
public void process() {
    
    MongoDatabase db = mongoClient.getDatabase("local");
    MongoCollection<RawBsonDocument> oplog = db.getCollection("oplog.rs", RawBsonDocument.class);

    RawBsonDocument lastOplogEntry = oplog.find().sort(new Document("$natural", -1)).first();

    BsonTimestamp lastTimestamp = (BsonTimestamp) lastOplogEntry.get("ts");

    System.out.println(lastTimestamp);

    Document query = new Document("ts", new Document("$lt", lastTimestamp));
    for (RawBsonDocument doc : oplog.find(query).noCursorTimeout(true)) {
        
        BsonString ns = (BsonString) doc.get("ns");
        BsonString op = (BsonString) doc.get("op");

        // ignore no-op
        if (!op.getValue().equals("n")) {
            OplogEntryKey key = new OplogEntryKey(ns.getValue(), op.getValue());
            EntryAccumulator accum = accumulators.get(key);
            if (accum == null) {
                accum = new EntryAccumulator(key);
                accumulators.put(key, accum);
            }
            long len = doc.getByteBuffer().asNIO().array().length;
            accum.addExecution(len);
        }

        if (stop) {
            mongoClient.close();
            report();
            break;
        }
    }
}
 
開發者ID:mhelmstetter,項目名稱:oplog-analyzer,代碼行數:37,代碼來源:OplogAnalyzer.java


注:本文中的com.mongodb.client.MongoDatabase.getCollection方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。