Example usage for com.mongodb MongoClient getDatabase

List of usage examples for com.mongodb MongoClient getDatabase

Introduction

In this page you can find the example usage for com.mongodb MongoClient getDatabase.

Prototype

public MongoDatabase getDatabase(final String databaseName) 

Source Link

Usage

From source file:course.homework.week2.RemoveLowest.java

License:Apache License

public static void main(final String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase numbersDB = client.getDatabase("students");
    MongoCollection<Document> grades = numbersDB.getCollection("grades");

    MongoCursor<Document> cursor = grades.find(eq("type", "homework")).sort(ascending("student_id", "score"))
            .iterator();/*from  w w  w  .  j  a v  a2 s  .co m*/

    Object studentId = -1;
    try {
        while (cursor.hasNext()) {
            Document entry = cursor.next();
            if (!entry.get("student_id").equals(studentId)) {
                System.out.println("Removing: " + entry);
                Object id = entry.get("_id");
                grades.deleteOne(eq("_id", id));

            }
            studentId = entry.get("student_id");
        }
    } finally {
        cursor.close();
    }
}

From source file:course.PrivateCloudController.java

License:Apache License

public PrivateCloudController(String mongoURIString) throws IOException {
    MongoCredential cred = MongoCredential.createCredential("admin", "cmpe283project1", "admin".toCharArray());
    final MongoClient mongoClient = new MongoClient(new ServerAddress("ds061721.mongolab.com:61721"),
            Arrays.asList(cred));
    final MongoDatabase blogDatabase = mongoClient.getDatabase("cmpe283project1");

    userDAO = new UserDAO(blogDatabase);
    sessionDAO = new SessionDAO(blogDatabase);

    statsDAO = new StatsDAO(mongoClient.getDatabase("cmpe283project1"));

    VMsDBCollection = mongoClient.getDatabase("cmpe283project1").getCollection("virtual_machines");
    if (VMsDBCollection != null) {
        System.out.println("VMs DB Collection found");
    } else//  ww w  .jav  a 2 s.c o m
        System.out.println("Sorry VMs DB Collection NOT found");

    cfg = createFreemarkerConfiguration();
    this.servInst = null;
    this.Path = null;
    //this.VMsDBCollection = null;

    servInst = new ServiceInstance(new URL(SJSULAB.getVCenterURL()), SJSULAB.getVCenterLogin(),
            SJSULAB.getVCenterPassword(), true);
    if (servInst == null) {
        System.out.println("Connection with " + SJSULAB.getVCenterURL() + " FAILED");
    } else {
        Path = servInst.getRootFolder();
        if (Path == null) {
            System.out.println("Getting Root Folder FAILED");
        }
    }
    setPort(8082);
    initializeRoutes();

    // Start the Statistics Collection Thread
    Thread statsThread = new Thread(new statsCollector());
    statsThread.start();

    //Start the Availability Manager Thread
    AvailabiltyManager av = new AvailabiltyManager();
    av.begin();

}

From source file:Dao.AccessDataNOSQL.java

License:Open Source License

/**
 * Metodo que se conecta a una coleccion de una base de datos no sql 
 * @param baseDatos la base de datos a la que se conecta
 * @param coleccion coleccion de la base de datos 
 * @return  devuelve la coleccion de la base de datos a la que se conecta 
 *///from   ww w.  jav a  2 s.c  o  m
public MongoCollection<Document> consultaBD(String baseDatos, String coleccion) {
    String direccion = "mongodb://" + getUser() + ":" + getPassword() + "@" + getCadenaConexion();
    //mongodb://bogdan:ar03pbo@ds033337.mongolab.com:33337/nosql
    MongoClientURI connectionString = new MongoClientURI(direccion);
    MongoClient mongoClient = new MongoClient(connectionString);

    MongoDatabase database = mongoClient.getDatabase(baseDatos);//nosql

    MongoCollection<Document> collec = database.getCollection(coleccion);

    return collec;
}

From source file:dao.DaoDocumentos.java

public boolean salvarCompra(Compra compra) {
    MongoClient client = new MongoClient("localhost", 27017);
    MongoDatabase dataBase = client.getDatabase("bdnc-loja");
    MongoCollection<Document> collection = dataBase.getCollection("vendas");
    collection.insertOne(compra.toDocument());
    client.close();//ww w .  jav a2s .  com
    return true;
}

From source file:dao.DaoDocumentos.java

public List<Compra> buscarCompras() {
    MongoClient client = new MongoClient("localhost", 27017);
    MongoDatabase dataBase = client.getDatabase("bdnc-loja");
    MongoCollection<Document> collection = dataBase.getCollection("vendas");
    List<Compra> compras = new ArrayList<>();
    MongoCursor<Document> cursor = collection.find().iterator();
    while (cursor.hasNext()) {
        Compra compra = new Compra();
        compras.add(compra.convertFromDocument(cursor.next()));
    }/*  www.j a v a 2  s  . c om*/
    client.close();
    return compras;
}

From source file:database.BFIdataTable.java

public BFIdataTable() {

    try {//ww  w  . j  ava  2s  .  c o  m
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        db = mongoClient.getDatabase("thesis");
        System.out.println("connected");
    } catch (Exception e) {
        Alert a = new Alert(Alert.AlertType.ERROR);
        a.setContentText("No MongoDB server found!!!");
        a.show();
        System.exit(0);
    }
}

From source file:db.migrations.mongo.V1_1__Test_Mongo_Migration.java

License:Apache License

@Override
public void migrate(MongoClient client) throws Exception {
    MongoDatabase testDb = client.getDatabase("flyway_test");
    MongoCollection<BasicDBObject> testCollection = testDb.getCollection("testCollection", BasicDBObject.class);
    BasicDBObject testObj = new BasicDBObject().append("name", "Mr. Meeseeks").append("color", "blue");

    testCollection.insertOne(testObj);/*ww  w. j a  va 2s  .c  o m*/
}

From source file:DBLayer.DBHandle.java

private DBHandle() {
    try {//  www  . ja  v a2 s. c  o  m

        // To connect to mongodb server
        // Now connect to your databases
        //            db = mongoClient.getDB("test");
        MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));

        db = mongoClient.getDatabase("schedule");
        job = db.getCollection(JOB);
        inventory = db.getCollection(INVENTORY);

        inventoryTransaction = db.getCollection(INVENTORYSTORE);

        System.out.println("Connect to database successfully");

        //         boolean auth = db.authenticate(myUserName, myPassword);
        //         System.out.println("Authentication: "+auth);         
        //            DBCollection coll = db.getCollection("mycol");
        //            System.out.println("Collection mycol selected successfully");
        //
        //            BasicDBObject doc = new BasicDBObject("title", "MongoDB").
        //                    append("description", "database").
        //                    append("likes", 100).
        //                    append("url", "http://www.tutorialspoint.com/mongodb/").
        //                    append("by", "tutorials point");
        //
        //            coll.insert(doc);
        //            System.out.println("Document inserted successfully");
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:de.adorsys.oauth.tokenstore.mongodb.MongoDbProvider.java

License:Apache License

@Produces
@ApplicationScoped/*w  w  w. ja va 2  s . c  o m*/
public MongoDatabase producesMongoDatabase() {
    String mongoUri = System.getProperty("oauth.mongodb.uri", "mongodb://localhost:27017");
    String mongoDb = System.getProperty("oauth.mongodb.database", "oauth");
    try {
        MongoClientURI clientURI = new MongoClientURI(mongoUri);
        LOG.info("use {}, database '{}', collection '{}'", createLogUri(clientURI), mongoDb,
                MdbTokenStore.COLLECTION_NAME);
        MongoClient mongoClient = new MongoClient(clientURI);
        return mongoClient.getDatabase(mongoDb);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:de.dfki.mmf.examples.craft_task_example.MongoDBWorldDescription.java

License:Open Source License

public MongoDatabase createCraftTaskDatabase() {
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase("craftdb");
    db.getCollection("User")
            .insertOne(new Document("worldObjectId", "User1")
                    .append("worldobjecttype", "User").append("position", new Document()
                            .append("xPosition", "1.1").append("yPosition", "0.25").append("zPosition", "0.2"))
                    .append("name", "Magdalena"));
    db.getCollection("Robot")
            .insertOne(new Document("worldObjectId", "Robot1")
                    .append("worldobjecttype", "Robot").append("position", new Document()
                            .append("xPosition", "0.0").append("yPosition", "0.0").append("zPosition", "0.0"))
                    .append("name", "Nao"));
    db.getCollection("Toolbox")
            .insertOne(new Document("worldObjectId", "Toolbox1").append("worldobjecttype", "Toolbox")
                    .append("position",
                            new Document().append("xPosition", "0.12").append("yPosition", "-0.22")
                                    .append("zPosition", "0.0"))
                    .append("content",
                            asList(new Document().append("toolName", "Drill").append("amount", "1"),
                                    new Document().append("toolName", "Screwdriver").append("amount", "3"),
                                    new Document().append("toolName", "Knife").append("amount", "5"),
                                    new Document().append("toolName", "Hammer").append("amount", "1"),
                                    new Document().append("toolName", "Sponge").append("amount", "2"),
                                    new Document().append("toolName", "Scissors").append("amount", "2"))

    ));/*  www. j a  v  a 2 s . c om*/
    db.getCollection("Hammer")
            .insertOne(
                    new Document("worldObjectId", "Hammer1").append("worldobjecttype", "Hammer")
                            .append("position", new Document().append("xPosition", "0.57")
                                    .append("yPosition", "-0.20").append("zPosition", "0.03"))
                            .append("belongsTo", "Toolbox1"));
    db.getCollection("Scissors")
            .insertOne(new Document("worldObjectId", "Scissors1").append("worldobjecttype", "Scissors")
                    .append("color", "black").append("size", "big").append("position", new Document()
                            .append("xPosition", "0.18").append("yPosition", "0.3").append("zPosition", "0.05"))
                    .append("belongsTo", "Toolbox1"));
    db.getCollection("Scissors")
            .insertOne(new Document("worldObjectId", "Scissors2").append("worldobjecttype", "Scissors")
                    .append("color", "blue-red").append("size", "small").append("position", new Document()
                            .append("xPosition", "0.6").append("yPosition", "0.25").append("zPosition", "0.01"))
                    .append("belongsTo", "Toolbox1"));
    db.getCollection("Sponge")
            .insertOne(new Document("worldObjectId", "Sponge1").append("worldobjecttype", "Sponge")
                    .append("color", "yellow").append("position", new Document().append("xPosition", "0.5")
                            .append("yPosition", "0.4").append("zPosition", "0.01"))
                    .append("belongsTo", "Toolbox1"));
    db.getCollection("Sponge")
            .insertOne(new Document("worldObjectId", "Sponge2").append("worldobjecttype", "Sponge")
                    .append("color", "green").append("position", new Document().append("xPosition", "0.25")
                            .append("yPosition", "-0.18").append("zPosition", "-0.05"))
                    .append("belongsTo", "Toolbox1"));

    return db;
}