Java 类com.mongodb.client.MongoDatabase 实例源码

项目:mongodb-crud    文件:QueryDocumentsImpl.java   
/**
 * This method retrieve all the document(s)
 */
@Override
public void getAllDocuments() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        FindIterable<Document> docs = collection.find(); //SELECT * FROM sample;
        for (Document doc : docs) {
            log.info(doc.getString("name"));
        }
    } catch (MongoException | ClassCastException e) {
        log.error("Exception occurred while insert Value using **BasicDBObject** : " + e, e);
    }
}
项目:mongodb-crud    文件:DeleteDocumentsImpl.java   
/**
 * This is delete the single document, which is first matched
 */
@Override
public void deleteOneDocument() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    Bson query = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        query = eq("name", "sundar");
        DeleteResult result = collection.deleteMany(query);
        if (result.wasAcknowledged()) {
            log.info("Single Document deleted successfully \nNo of Document Deleted : " + result.getDeletedCount());
        }
    } catch (MongoException e) {
        log.error("Exception occurred while delete Single Document : " + e, e);
    }
}
项目:mongodb-crud    文件:DeleteDocumentsImpl.java   
/**
 * This is deleted delete all document(s), which is matched
 */
@Override
public void deleteManyDocument() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    Bson query = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        query = lt("age", 20);
        DeleteResult result = collection.deleteMany(query);
        if (result.wasAcknowledged()) {
            log.info("Document deleted successfully \nNo of Document(s) Deleted : "
                    + result.getDeletedCount());
        }
    } catch (MongoException e) {
        log.error("Exception occurred while delete Many Document : " + e, e);
    }
}
项目:digital-display-garden-iteration-3-sixguysburgers-fries    文件:UnorganizedTests.java   
@Test
public void incrementMetadata() {
//This method is called from inside of getPlantByPlantId();
    boolean myPlant = plantController.
            incrementMetadata("58d1c36efb0cac4e15afd278", "pageViews");
    assertFalse(myPlant);
    boolean myPlant2 = plantController.incrementMetadata("16001.0","pageViews");
    assertTrue(myPlant2);


//This is necessary to test the data separately from getPlantByPlantId();
    Document searchDocument = new Document();
    searchDocument.append("id", "16001.0");
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection<Document> plantCollection = db.getCollection("plants");
    String before = JSON.serialize(plantCollection.find(searchDocument));
    plantController.incrementMetadata("16001.0","pageViews");
    String after = JSON.serialize(plantCollection.find(searchDocument));

    assertFalse(before.equals(after));
}
项目:rocketmq-flink-plugin    文件:MongoManager.java   
/**
 * @param dbName         表名
 * @param collectionName 集合名
 * @param saveJson       待存入JSON
 * @return 插入状态或异常信息
 */
@SuppressWarnings("unchecked")
public JSONObject executeInsert(String dbName, String collectionName, JSONObject saveJson) {
    JSONObject resp = new JSONObject();
    try {
        MongoDatabase db = mongoClient.getDatabase(dbName);
        MongoCollection coll = db.getCollection(collectionName);
        Document doc = Document.parse(saveJson.toString());
        coll.insertOne(doc);
    } catch (MongoTimeoutException e1) {
        e1.printStackTrace();
        resp.put("ReasonMessage", e1.getClass() + ":" + e1.getMessage());
        return resp;
    } catch (Exception e) {
        e.printStackTrace();
        resp.put("ReasonMessage", e.getClass() + ":" + e.getMessage());
    }
    return resp;
}
项目:digital-display-garden-iteration-4-dorfner-v2    文件:FlowerRating.java   
@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);
}
项目:mongodb-crud    文件:UpdateDocumentsImpl.java   
/**
 * 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);
    }
}
项目:BingoChess    文件:BingoChessChallenge.java   
public BingoChessChallenge(String[] args) {
    announcer = new Chatter(args[0]);
    lichs = new HashMap<String,Lichesser>();
    chessplayers = new HashMap<String,ChessPlayer>();
    chessgames = new HashMap<String,LichessGame>();
    BingoPlayer.SQUARE_BAG = new Vector<Dimension>();
    for (int x=0;x<8;x++)
    for (int y=0;y<8;y++)
    BingoPlayer.SQUARE_BAG.add(new Dimension(x,y));
    initIRC(args[0], args[1], args[2], args[3]);
    loadAdmins("res/admins.txt");
    serv = new BingoServ(Integer.parseInt(args[4]),this);
    serv.startSrv();
    bingoURL = args[5];
    MongoClientURI connStr = new MongoClientURI("mongodb://bingobot:" + args[6] + "@localhost:27017/BingoBase");
    MongoClient mongoClient = new MongoClient(connStr);
    MongoDatabase bingoBase = mongoClient.getDatabase("BingoBase");
    playData = bingoBase.getCollection("players");
}
项目:mongodb-crud    文件:InsertDocumentsImpl.java   
/**
 * 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);
    }
}
项目:rebase-server    文件:MongoDBs.java   
private static void initCollections(MongoDatabase db) {
    try {
        db.createCollection("users");
        db.createCollection("categories");
        db.createCollection("feeds");
        db.createCollection("licenses");
    } catch (Exception e) {
        Log.w(TAG, "[attemptCreateCollections] " + e.getMessage());
    }
    users = db.getCollection("users");
    categories = db.getCollection("categories");
    feeds = db.getCollection("feeds");
    licenses = db.getCollection("licenses");

    users.createIndex(
        Indexes.ascending(User.USERNAME),
        new IndexOptions().unique(true));

    categories.createIndex(
        Indexes.ascending(Category.OWNER, Category.KEY),
        new IndexOptions().unique(true));
}
项目:Jerkoff    文件:MongoDBDaoImpl.java   
@Override
public List<Document> find(String collection, String signature) {
    List<Document> res = new ArrayList<Document>();
    try {
        MongoDatabase db = mongoClient.getDatabase(databaseName);
        MongoCollection<Document> coll = db.getCollection(collection);
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("signature", signature);
        Iterable<Document> docs = coll.find(searchQuery);
        for (Document doc : docs) {
            res.add(doc);
        }
    } catch (Exception e) {
        LOG.error(e);
    }
    return res;
}
项目:Babler    文件:DAO.java   
/**
 * 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;
    }

}
项目:digital-display-garden-iteration-2-spraguesanborn    文件:ExcelParser.java   
public static void populateDatabase(String[][] cellValues){
    MongoClient mongoClient = new MongoClient();
    MongoDatabase ddg = mongoClient.getDatabase("ddg");
    MongoCollection plants = ddg.getCollection("flowers");
    plants.drop();

    String[] keys = getKeys(cellValues);

    for (int i = 4; i < cellValues.length; i++){
        Map<String, String> map = new HashMap<String, String>();
        for(int j = 0; j < cellValues[i].length; j++){
            map.put(keys[j], cellValues[i][j]);
        }

        Document doc = new Document();
        doc.putAll(map);
        doc.append("thumbsUp", 0);
        doc.append("flowerVisits", 0);
        plants.insertOne(doc);
    }
}
项目:Jerkoff    文件:MongoTest.java   
@Test
@Ignore
public void testInsert() {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    try {
        MongoDatabase db = mongoClient.getDatabase("prova");
        MongoCollection<Document> coll = db.getCollection("prova");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("signature", "void test()");
        map.put("param", convert(new Object[0]));
        map.put("returnValue", 1);
        map.put("exception", convert(new IllegalAccessError("prova")));
        Document doc = new Document(map);
        coll.insertOne(doc);
        LOG.info(doc);
    } catch (Exception e) {
        LOG.error(e);
    } finally {
        mongoClient.close();
    }
}
项目:digital-display-garden-iteration-4-dorfner-v2    文件:FlowerRating.java   
@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);
}
项目:Jerkoff    文件:MongoTest.java   
@Test
@Ignore
public void testRead() {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    try {
        MongoDatabase db = mongoClient.getDatabase("prova");
        MongoCollection<Document> coll = db.getCollection("prova");
        FindIterable<Document> res = coll.find();
        for (Document doc : res) {
            String thisObj = doc.getString("this");
            LOG.info(thisObj);
            String thisClass = doc.getString("thisClass");
            LOG.info(thisClass);
            Gson gson = new Gson();
            Class<?> cl = Class.forName(thisClass);
            Object obj = gson.fromJson(thisObj, cl);
            LOG.info(obj);
        }
    } catch (Exception e) {
        LOG.error(e);
    } finally {
        mongoClient.close();
    }
}
项目:athena    文件:FeatureDatabaseMgmtManager.java   
public HashMap<String, MongoCollection> getCollectionList(MongoDatabase mongoDatabase) {
    HashMap<String, MongoCollection> dbCollectionList = new HashMap<String, MongoCollection>();
    String[] tableNameList = {AthenaFeatureField.ERROR_MSG, AthenaFeatureField.FLOW_REMOVED,
            AthenaFeatureField.PACKET_IN,
            AthenaFeatureField.PORT_STATUS, AthenaFeatureField.FLOW_STATS, AthenaFeatureField.QUEUE_STATS,
            AthenaFeatureField.AGGREGATE_STATS, AthenaFeatureField.TABLE_STATS, AthenaFeatureField.PORT_STATS};

    for (String tableName : tableNameList) {
        MongoCollection dbCollection = mongoDatabase.getCollection(tableName);
        if (dbCollection == null) {
            mongoDatabase.createCollection(tableName);
            dbCollection = mongoDatabase.getCollection(tableName);
        }
        dbCollectionList.put(tableName, dbCollection);
    }

    return dbCollectionList;
}
项目:digital-display-garden-iteration-3-sixguysburgers-fries    文件:TestPlantComment.java   
@Test
public void successfulInputOfComment() throws IOException {
    String json = "{ plantId: \"58d1c36efb0cac4e15afd278\", comment : \"Here is our comment for this test\" }";

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

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

    long contains = commentDocuments.count();
    assertEquals(1, contains);

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

    Document fromDb = iter.next();

    assertEquals("Here is our comment for this test", fromDb.getString("comment"));
    assertEquals("16040.0", fromDb.get("commentOnPlant"));
    assertEquals("second uploadId", fromDb.get("uploadId"));
}
项目:digital-display-garden-iteration-3-sixguysburgers-fries    文件:FlowerRating.java   
@Test
public void AddFlowerRatingReturnsTrueWithValidInput() throws IOException{

    assertTrue(plantController.addFlowerRating("58d1c36efb0cac4e15afd202", true, "first uploadId"));

    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"));
    assertEquals(new ObjectId("58d1c36efb0cac4e15afd202"),rating.get("ratingOnObjectOfId"));
}
项目:digital-display-garden-iteration-4-dorfner-v2    文件:TestPlantComment.java   
@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"));
  }
项目:rocketmq-flink-plugin    文件:MongoManager.java   
public JSONObject executeCount(String dbName, String collectionName, JSONObject reqJson) {

        MongoDatabase db = mongoClient.getDatabase(dbName);
        MongoCollection coll = db.getCollection(collectionName);

        JSONObject resp = new JSONObject();
        Document doc = Document.parse(reqJson.toString());
        long count = coll.count(doc);
        resp.put("Data", count);
        return resp;
    }
项目:mongodb-crud    文件:InsertDocumentsImpl.java   
/**
 * This method insert the more than one document at a time
 */
@Override
public void insertMultipleDocuments() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());

        Document journal = new Document("item", "journal")
                .append("qty", 25).append("tags", asList("blank", "red"));

        Document journalSize = new Document("h", 14).append("w", 21)
                .append("uom", "cm");
        journal.put("size", journalSize);

        Document mat = new Document("item", "mat").append("qty", 85)
                .append("tags", singletonList("gray"));

        Document matSize = new Document("h", 27.9).append("w", 35.5)
                .append("uom", "cm");
        mat.put("size", matSize);

        Document mousePad = new Document("item", "mousePad").append("qty",
                25).append("tags", asList("gel", "blue"));

        Document mousePadSize = new Document("h", 19).append("w", 22.85)
                .append("uom", "cm");
        mousePad.put("size", mousePadSize);
        collection.insertMany(asList(journal, mat, mousePad));
        log.info("Multiple Document Insert Successfully...");
    } catch (MongoException | ClassCastException e) {
        log.error("Exception occurred while insert **Multiple Document** : " + e, e);
    }
}
项目:digital-display-garden-iteration-2-spraguesanborn    文件:FlowerControllerSpec.java   
@Test
public void testUploadFile() {
    String filePath = "/IDPH_STD_Illinois_By_County_By_Sex.xlsx";
    Object object = new Object();
    InputStream excelFile = object.getClass().getResourceAsStream(filePath);

    flowerController.uploadFile(excelFile);

    MongoClient mongoClient = new MongoClient();
    MongoDatabase ddg = mongoClient.getDatabase("ddg");
    MongoCollection flowers = ddg.getCollection("flowers");
    assertEquals(1664, flowers.count());
}
项目:rocketmq-flink-plugin    文件:MongoManager.java   
/**
 * @param dbName         库名
 * @param collectionName 集合名
 * @param json1          条件
 * @param json2          保存doc
 * @return upsert结果信息
 */
public JSONObject executeUpsert(String dbName, String collectionName, JSONObject json1, JSONObject json2) {
    JSONObject resp = new JSONObject();
    try {
        MongoDatabase db = mongoClient.getDatabase(dbName);
        MongoCollection coll = db.getCollection(collectionName);
        JSONObject saveJson = new JSONObject();
        saveJson.put("$set", json2);
        Document doc1 = Document.parse(json1.toString());
        Document doc2 = Document.parse(saveJson.toString());
        UpdateOptions up = new UpdateOptions();
        up.upsert(true);
        UpdateResult ur = coll.updateOne(doc1, doc2, up);
        if (ur.isModifiedCountAvailable()) {
            if (json1.containsKey(ID)) {
                resp.put("Data", json1.get(ID));
            } else {
                resp.put("Data", json1);
            }
        }
    } catch (MongoTimeoutException e1) {
        e1.printStackTrace();
        resp.put("ReasonMessage", e1.getClass() + ":" + e1.getMessage());
        return resp;
    } catch (Exception e) {
        e.printStackTrace();
        resp.put("ReasonMessage", e.getClass() + ":" + e.getMessage());
    }
    return resp;
}
项目:oplog-analyzer    文件:OplogAnalyzer.java   
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;
        }
    }
}
项目:Babler    文件:DAO.java   
/**
 * Returns a MongoCollection based on Model Class
 * @param type Model Class
 * @return MongoCollection for that class
 */
public static MongoCollection getCollectionForClass(Class type) {
    MongoDatabase db = MongoDB.INSTANCE.getDatabase("scraping");
    String collectionName = "";
    if (Tweet.class == type)
        collectionName = "tweets";
    else if (BlogPost.class == type)
        collectionName = "blogPosts";
    else if (ForumPost.class == type)
        collectionName = "forumPosts";

    return db.getCollection(collectionName, BasicDBObject.class);
}
项目:Babler    文件:DAO.java   
/**
 * deletes an entry from the DB
 * @param entry to delete
 */
public static void deleteEntry(DBEntry entry) {
    if(entry == null)
        return;

    MongoDatabase db = MongoDB.INSTANCE.getDatabase("scraping");
    String collectionName = getCollectionName(entry);

    MongoCollection collection = db.getCollection(collectionName, BasicDBObject.class);
    collection.deleteOne(eq("_id",entry.getId()));
}
项目:acmeair-modular    文件:FlightServiceImpl.java   
@PostConstruct
public void initialization() {
    MongoDatabase database = ConnectionManager.getConnectionManager().getDB();
    flight = database.getCollection("flight");
    flightSegment = database.getCollection("flightSegment");
    airportCodeMapping = database.getCollection("airportCodeMapping");
}
项目:nifi-nars    文件:StoreInMongoIT.java   
@After
public void tearDown() throws Exception {
    if (null != mongo) {
        MongoClient client = mongo.getMongoClient();
        if (client != null) {
            MongoDatabase db = client.getDatabase(MONGO_DATABASE_NAME);
            if (db != null) {
                db.drop();
            }
            client.close();
        }
    }
}
项目:nifi-nars    文件:UpdateMongoIT.java   
@After
public void tearDown() throws Exception {
    if (null != mongo) {
        MongoClient client = mongo.getMongoClient();
        MongoDatabase db = client.getDatabase(MONGO_DATABASE_NAME);
        if (db != null) {
            db.drop();
        }
        client.close();
    }
}
项目:QDrill    文件:MongoRecordReader.java   
private void init(MongoSubScan.MongoSubScanSpec subScanSpec) {
  List<String> hosts = subScanSpec.getHosts();
  List<ServerAddress> addresses = Lists.newArrayList();
  for (String host : hosts) {
    addresses.add(new ServerAddress(host));
  }
  MongoClient client = plugin.getClient(addresses);
  MongoDatabase db = client.getDatabase(subScanSpec.getDbName());
  collection = db.getCollection(subScanSpec.getCollectionName());
}
项目:QDrill    文件:MongoSchemaFactory.java   
@Override
public List<String> load(String dbName) throws Exception {
  try {
    MongoDatabase db = client.getDatabase(dbName);
    List<String> collectionNames = new ArrayList<>();
    db.listCollectionNames().into(collectionNames);
    return collectionNames;
  } catch (MongoException me) {
    logger.warn("Failure while getting collection names from '{}'. {}",
        dbName, me.getMessage());
    return Collections.emptyList();
  } catch (Exception e) {
    throw new DrillRuntimeException(e.getMessage(), e);
  }
}
项目:QDrill    文件:MongoTestSuit.java   
private static void createDbAndCollections(String dbName,
    String collectionName, String indexFieldName) {
  MongoDatabase db = mongoClient.getDatabase(dbName);
  MongoCollection<Document> mongoCollection = db
      .getCollection(collectionName);
  if (mongoCollection == null) {
    db.createCollection(collectionName);
    mongoCollection = db.getCollection(collectionName);
  }
  IndexOptions indexOptions = new IndexOptions().unique(true)
      .background(false).name(indexFieldName);
  Bson keys = new Document(indexFieldName, Integer.valueOf(1));
  mongoCollection.createIndex(keys, indexOptions);
}
项目:Java-9-Programming-Blueprints    文件:Producers.java   
@Produces
private MongoDatabase getDatabase() {
    if (database == null) {
        database = getMongoClient().getDatabase("monumentum");
    }

    return database;
}
项目:nifi-nars    文件:UpdateMongoIT.java   
@Test
public void testUpsertFalse() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(new UpdateMongo());
    addMongoService(runner);
    runner.setProperty(MongoProps.DATABASE, MONGO_DATABASE_NAME);
    runner.setProperty(MongoProps.COLLECTION, "upsert_test");
    runner.setProperty(MongoProps.UPDATE_QUERY_KEYS, "d.id");
    runner.setProperty(MongoProps.UPDATE_KEYS, "d.g");
    runner.setProperty(MongoProps.UPDATE_OPERATOR, "$unset");
    runner.setProperty(MongoProps.UPSERT, "false");

    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 that document wasn't inserted
    MongoClient client = mongo.getMongoClient();
    MongoDatabase db = client.getDatabase(MONGO_DATABASE_NAME);
    if (db != null) {
        MongoCollection<Document> collection = db.getCollection("upsert_test");
        assertEquals(0, collection.count());
    }
}
项目:spring-multitenancy    文件:MongoBasicOperations.java   
@Override
public boolean exist(String collectionName) {
    MongoDatabase database = dataSource.getDataSource();
    MongoCursor<String> result =  database.listCollectionNames().iterator();

    while(result.hasNext()){
        if(result.next().equalsIgnoreCase(collectionName)){
            return true;
        }
    }

    return false;
}
项目:pac4j-plus    文件:MongoServer.java   
public void start(final int port) {
    MongodStarter starter = MongodStarter.getDefaultInstance();

    try {
        IMongodConfig mongodConfig = new MongodConfigBuilder()
                .version(Version.Main.PRODUCTION)
                .net(new Net(port, Network.localhostIsIPv6()))
                .build();

        mongodExecutable = starter.prepare(mongodConfig);
        mongodExecutable.start();

        // populate
        final MongoClient mongo = new MongoClient("localhost", port);
        final MongoDatabase db = mongo.getDatabase("users");
        db.createCollection("users");
        final MongoCollection<Document> collection = db.getCollection("users");
        final PasswordEncoder encoder = new BasicSaltedSha512PasswordEncoder(SALT);
        final String password = encoder.encode(PASSWORD);
        Map<String, Object> properties1 = new HashMap<>();
        properties1.put(USERNAME, GOOD_USERNAME);
        properties1.put(PASSWORD, password);
        properties1.put(FIRSTNAME, FIRSTNAME_VALUE);
        collection.insertOne(new Document(properties1));
        Map<String, Object> properties2 = new HashMap<>();
        properties2.put(USERNAME, MULTIPLE_USERNAME);
        properties2.put(PASSWORD, password);
        collection.insertOne(new Document(properties2));
        Map<String, Object> properties3 = new HashMap<>();
        properties3.put(USERNAME, MULTIPLE_USERNAME);
        properties3.put(PASSWORD, password);
        collection.insertOne(new Document(properties3));

    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}
项目:tapir    文件:SipMessageMongoCron.java   
@Autowired
public SipMessageMongoCron(@Value("${mongo.partition}") String partition,
                           @Value("${ttl.registers}") String ttlRegisters,
                           @Value("${ttl.calls}") String ttlCalls,
                           MongoDatabase db) {
    this.partition = PartitionFactory.ofPattern(partition);
    this.ttlRegisters = PartitionFactory.ofPattern(ttlRegisters).duration();
    this.ttlCalls = PartitionFactory.ofPattern(ttlCalls).duration();
    this.db = db;
}