Example usage for com.mongodb.client MongoDatabase getCollection

List of usage examples for com.mongodb.client MongoDatabase getCollection

Introduction

In this page you can find the example usage for com.mongodb.client MongoDatabase getCollection.

Prototype

MongoCollection<Document> getCollection(String collectionName);

Source Link

Document

Gets a collection.

Usage

From source file:com.thaonedroid.mongodbexercise.MongoDB.java

public static void main(String[] args) {
    try {/*from  w  w w.j a  v a 2  s .  c  o  m*/
        MongoClientURI connStr = new MongoClientURI("mongodb://localhost:27017");
        MongoClient mongoClient = new MongoClient(connStr);

        MongoDatabase db = mongoClient.getDatabase("twitter");
        MongoCollection<Document> collection = db.getCollection("tweets");

        Scanner scanner = new Scanner(System.in);
        int input;
        OUTER: do {
            start();
            input = scanner.nextInt();
            switch (input) {
            case 1:
                //System.out.println("Distinct Twitter users : " + query.totalUsers());
                System.out.println("Question : " + q1);
                execute(query.totalUsers());
                break;
            case 2:
                //execute(query.linkOthers());
                System.out.println("Question : " + q2);
                System.out.println("Answer : Query hasn't been properly figured out yet");
                break;
            case 3:
                //execute(query.mostMentioned());
                System.out.println("Question : " + q3);
                System.out.println("Answer : Query hasn't been properly figured out yet");
                break;
            case 4:
                System.out.println("Question : " + q4);
                execute(query.mostActive());
                //System.out.println("Most active users : " + query.mostActive());
                break;
            case 5:
                System.out.println("Question : " + q5);
                execute(query.mostGrumpy());
                //System.out.println("Most grumpy users : " + query.mostGrumpy());
                break;
            case 6:
                System.out.println("Question : " + q6);
                execute(query.mostHappy());
                //System.out.println("Most happy users : " + query.mostHappy());
                break;
            case 7:
                break OUTER;
            default:
                break;
            }
        } while (true);
        mongoClient.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ":" + e.getMessage());
    }
}

From source file:com.threecrickets.prudence.cache.HazelcastMongoDbMapStore.java

License:LGPL

/**
 * The MongoDB collection used for the store.
 * /*from   w w w .j a va 2s . c  om*/
 * @return The MongoDB collection
 */
public MongoCollection<Document> getCollection() {
    if (collection == null) {
        Component component = InstanceUtil.getComponent();
        if (component != null) {
            MongoClient client = (MongoClient) component.getContext().getAttributes()
                    .get(MONGODB_CLIENT_ATTRIBUTE);
            if (client != null) {
                MongoDatabase database = client.getDatabase("prudence");
                if (database != null)
                    collection = database.getCollection(collectionName);
            }
        }
    }

    if (collection == null)
        throw new RuntimeException(
                "MongoDB client must be configured in order to use HazelcastMongoDbMapStore");

    return collection;
}

From source file:com.threecrickets.prudence.cache.MongoDbCache.java

License:LGPL

/**
 * Constructor./* www.  jav  a  2  s.  c o  m*/
 * 
 * @param client
 *        The MongoDB client
 * @param databaseName
 *        The MongoDB database name
 * @param collectionName
 *        The name of the collection to use for the cache
 */
public MongoDbCache(MongoClient client, String databaseName, String collectionName) {
    this.client = client;
    MongoDatabase database = client.getDatabase(databaseName);
    cacheCollection = database.getCollection(collectionName);
    try {
        cacheCollection.createIndex(TAG_INDEX);
        cacheCollection.createIndex(EXPIRATION_DATE_INDEX);
        up();
    } catch (com.mongodb.MongoSocketException x) {
        down();
    }
}

From source file:com.torodb.testing.mongodb.docker.ReplicaSetContract.java

License:Apache License

@Test
default void genericTest() {
    int docsToInsert = 100;

    try (ReplicaSet replicaSet = getReplicaSet(simpleReplConfig())) {
        replicaSet.startAsync();//  ww w  .  j  av a2  s  .c o m
        replicaSet.awaitRunning();

        getLogger().debug("Inserting {} documents on {}", docsToInsert, replicaSet.getReplSetName());
        MongoDatabase db = replicaSet.getClient().getDatabase("testDb");
        MongoCollection<Document> col = db.getCollection("testCol")
                .withWriteConcern(replicaSet.getTotalWriteConcern());
        for (int i = 0; i < docsToInsert; i++) {
            col.insertOne(new Document());
        }

        Assertions.assertEquals(docsToInsert, col.count());

        for (ReplMongod mongo : replicaSet.getMongos()) {
            getLogger().debug("Assertions on node {}", mongo);

            long oplogCount = mongo.getMongoClient().getDatabase("local").getCollection("rs.oplog").count();

            Assertions.assertNotEquals(0, oplogCount, "Oplog on node " + mongo + " is empty");

            long colCount = mongo.getMongoClient().getDatabase("testDb").getCollection("testCol").count();

            Assertions.assertEquals(docsToInsert, colCount, "Incorrect number of documents replicated");
        }
    }
}

From source file:com.torodb.testing.mongodb.docker.ShardedClusterContract.java

License:Apache License

@Test
default void startAndStop() {

    try (ShardedCluster cluster = getShardedCluster(smallShardedClusterConfig())) {
        getLogger().debug("Starting cluster...");
        cluster.startAsync();/*w  ww  .j  ava 2 s  .  c om*/
        cluster.awaitRunning();

        getLogger().debug("Cluster has been started");
        getLogger().debug("Configuring cluster");

        cluster.enableSharding("testDb");
        cluster.shardCollection("testDb", "testCol");
        cluster.setChunckSize(1);

        getLogger().debug("Sharding has been configured");

        getLogger().debug("Inserting documents");

        int docsToInsert = 10_000;

        MongoDatabase db = cluster.getClient().getDatabase("testDb");
        MongoCollection<Document> col = db.getCollection("testCol");
        for (int i = 0; i < docsToInsert; i++) {
            col.insertOne(new Document());
        }

        getLogger().debug("Documents have been inserted");

        Assertions.assertEquals(docsToInsert, col.count());
    }
}

From source file:com.u2apple.rt.db.dao.DeviceLogDao.java

private MongoCollection<Document> getDeviceLog() {
    MongoClient mongoClient = new MongoClient("localhost");
    MongoDatabase db = mongoClient.getDatabase("recognition");
    return db.getCollection("log");
}

From source file:com.um.mongodb.converter.EhealthRecordConverter.java

/**
 * /*from www.  ja v a 2  s  . c o  m*/
 * @param ags
 * @return 
 */
public static int main(String[] ags) {

    MongoClient client = new MongoClient("localhost", 27017);

    if (client != null) {
        System.out.println("success");
    } else {
        System.out.println("failed");
    }

    MongoDatabase database = client.getDatabase("db");

    if (database == null) {
        System.out.println("db is null");
    } else {
        System.out.println("db is not null");
    }

    MongoCollection<Document> collection = database.getCollection("ehealth");
    //      System.out.println(collection.count());

    MongoCursor<Document> cursor = collection
            .find(new BasicDBObject("ehealthrecord.registrationno", "600025873102")).iterator();

    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }

    return 0;
}

From source file:com.zns.vehicles.service.dao.impl.VehicleDAOImpl.java

private void dbPostUtil(String collection, Document doc) {
    MongoClient mongoClient = null;/*from  ww w .ja va 2 s. c  o  m*/
    try {
        mongoClient = new MongoClient(props.getProperty(HOST), PORT);
        MongoDatabase db = mongoClient.getDatabase("vehicleApp");

        db.getCollection(collection).insertOne(doc);

    } catch (MongoClientException e) {
        log.error("Error while connecting to DB...");
        e.printStackTrace();
    } catch (MongoException e) {
        log.error("General mongo error");
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        log.error("Illegal argument exception...");
        e.printStackTrace();
    } finally {
        log.info("submitted request has been persisted sucessfully");
        mongoClient.close();
    }
}

From source file:com.zns.vehicles.service.dao.impl.VehicleDAOImpl.java

private ArrayList<String> dbGetUtil(RetrievalRequest requestPartial) {

    MongoClient mongoClient = null;/*w ww  .  j a  va2s .  co  m*/
    ArrayList<String> results = new ArrayList<String>();

    try {
        mongoClient = new MongoClient(props.getProperty(HOST), PORT);
        MongoDatabase db = mongoClient.getDatabase("vehicleApp");

        log.info("querying this collection >>>>>>>>>>>>>>>>>>>>>>>>>> "
                + db.getCollection("vehicles").toString());
        log.info("looking for vehicle type:::::::: " + requestPartial.getVehicleType());

        FindIterable<Document> iterable = db.getCollection("vehicles")
                .find(new Document("username", requestPartial.getUserName()).append("vehicleType",
                        requestPartial.getVehicleType()));

        iterable.forEach(new Block<Document>() {
            @Override
            public void apply(final Document document) {
                log.info("result>>>>>>>>>>>>>> " + document.toString());
                results.add(document.toJson());
            }
        });

    } catch (MongoClientException e) {
        log.error("Error while connecting to DB...");
        e.printStackTrace();
    } catch (MongoException e) {
        log.error("General mongo error");
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        log.error("Illegal argument exception...");
        e.printStackTrace();
    } finally {
        mongoClient.close();
    }
    log.info("arraylist contents for search::::::::: " + results.size());
    return results;
}

From source file:consultasEntradaSaidaArquivo.LeituraXLS.java

public static void leituraDeArquivos(MongoDatabase db) throws IOException, BiffException {
    File folder = new File("src/arquivosPlataformaP56");
    File[] listOfFiles = folder.listFiles();

    MongoCollection myCollection = db.getCollection("pt");
    myCollection.drop();/* w  w w . j av  a  2 s .  co  m*/

    for (File file : listOfFiles) {
        if (file.isFile()) {
            lerArquivo(db, file.getName());
        }
    }
}