Example usage for com.mongodb DBCollection insert

List of usage examples for com.mongodb DBCollection insert

Introduction

In this page you can find the example usage for com.mongodb DBCollection insert.

Prototype

public WriteResult insert(final List<? extends DBObject> documents) 

Source Link

Document

Insert documents into a collection.

Usage

From source file:com.tml.pathummoto.Dao.ModelDao.java

public void addModel(Model model) {
    MongoClient mongoClient = new MongoClient("localhost", 27017);

    // Now connect to your databases
    DB db = mongoClient.getDB("pathumdb");
    System.out.println("Connect to database successfully");

    DBCollection coll = db.getCollection("model");

    BasicDBObject doc = new BasicDBObject("title", "model").append("_id", model.getModelName());

    coll.insert(doc);
    System.out.println("Document inserted successfully");

}

From source file:com.tml.pathummoto.Dao.PartDao.java

public void addPart(Part part) {
    MongoClient mongoClient = new MongoClient("localhost", 27017);

    // Now connect to your databases
    DB db = mongoClient.getDB("pathumdb");
    System.out.println("Connect to database successfully");

    DBCollection coll = db.getCollection("part");

    BasicDBObject doc = new BasicDBObject("title", "part").append("_id", part.getPartNo())
            .append("Part Name", part.getPartName()).append("Model Name", part.getModelName())
            .append("Image No", part.getImageNo()).append("Part Type", part.getPartType()).append("quant", 0);

    try {/*from  w  w w .  j  a va  2  s .  c o  m*/
        coll.insert(doc);
    } catch (Exception e) {
        System.out.println("Document inserted successfully");
    }
}

From source file:com.tml.pathummoto.Dao.PartDao.java

public void addMainPart(MainPart mainpart) {
    MongoClient mongoClient = new MongoClient("localhost", 27017);

    // Now connect to your databases
    DB db = mongoClient.getDB("pathumdb");
    System.out.println("Connect to database successfully");

    DBCollection coll = db.getCollection("mainpart");

    BasicDBObject doc = new BasicDBObject("title", "mainpart").append("path", mainpart.getImageName())
            .append("Model Name", mainpart.getModelName()).append("Part Type", mainpart.getPartType());

    coll.insert(doc);
    System.out.println("Document inserted successfully");

}

From source file:com.tml.pathummoto.Dao.UserDao.java

public void signup(User user) {

    try {/*  w  w w.ja v a 2 s .c  om*/

        // To connect to mongodb server
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // Now connect to your databases
        DB db = mongoClient.getDB("pathumdb");
        System.out.println("Connect to database successfully");

        DBCollection coll = db.getCollection("user");
        System.out.println("Collection mycol selected successfully");

        BasicDBObject doc = new BasicDBObject("title", user.getName()).append("password", user.getPassword());

        coll.insert(doc);
        System.out.println("Document inserted successfully");
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }

}

From source file:com.ultratechnica.mongodb.Main.java

License:Apache License

public static void main(String[] args) {

    log.info("=============================================================================================\n"
            + "                       _   _     _                 \n"
            + " |\\/|  _  ._   _   _  | \\ |_)   |_)  _  ._   _ |_  \n"
            + " |  | (_) | | (_| (_) |_/ |_)   |_) (/_ | | (_ | | \n"
            + "               _|                                  \n"
            + "Copyright 2013 Keith Bishop, Ultratechnica Ltd, http://ultratechnica.com\n"
            + "Licensed to Apache "
            + "=============================================================================================\n");
    Options options = getOptions();/*from w w w .j av a2 s . co m*/

    CommandLine commandLine = parseArgs(args, options);

    MongoClient client = null;

    if (commandLine.hasOption("host") && commandLine.hasOption("port")) {

        String host = commandLine.getOptionValue("host");
        String port = commandLine.getOptionValue("port");

        try {

            client = new MongoClient(host, Integer.parseInt(port));
        } catch (UnknownHostException e) {
            log.error("Unable to connect to host [{}] on port [{}]", host, port);
        }
    } else if (options.hasOption("host")) {

        String host = commandLine.getOptionValue("host");

        try {
            client = new MongoClient(host);
        } catch (UnknownHostException e) {
            log.error("Unable to connect to host [{}] on default port ()", host);
        }
    } else {

        try {
            client = new MongoClient();
        } catch (UnknownHostException e) {
            log.error("Unable to connect default host ({}) on default port ()", DEFAULT_HOST, DEFAULT_PORT);
        }
    }

    if (client == null) {
        System.out.println("Exiting, due to previous connection errors");
        System.exit(1);
    }

    ServerAddress clientAddress = client.getAddress();
    log.info("Connected to MongoDB [{}]", clientAddress);

    MongoClientOptions mongoClientOptions = client.getMongoClientOptions();

    log.info("=============================================================================================\n"
            + "Using Mongo Client options:\n" + "\tConnections per host: "
            + mongoClientOptions.getConnectionsPerHost() + "\n" + "\tConect timeout: "
            + mongoClientOptions.getConnectTimeout() + " \n" + "\tSocket timeout: "
            + mongoClientOptions.getSocketTimeout() + "\n" + "\tMax Wait time: "
            + mongoClientOptions.getMaxWaitTime() + "\n" + "\tMax Auto connect retry time: "
            + mongoClientOptions.getMaxAutoConnectRetryTime() + "\n"
            + "\tMax threads allowed to block for conneciton multipler: "
            + mongoClientOptions.getThreadsAllowedToBlockForConnectionMultiplier() + "\n" + "\tWrite concern: "
            + mongoClientOptions.getWriteConcern() + "\n" + "\tRead Preference: "
            + mongoClientOptions.getReadPreference() + "\n"
            + "=============================================================================================\n");

    String items = commandLine.getOptionValue("n");

    int numberOfItems = 0;
    try {
        numberOfItems = Integer.parseInt(items);
    } catch (NumberFormatException e) {
        log.error("The parameter provided for -n was not an integer [{}]", items);
        System.exit(1);
    }

    DB local = client.getDB("local");

    DBCollection collection = local.getCollection(DEFAULT_COLLECTION_NAME);

    log.info("Starting benchmark, inserting [{}] items into collection [{}]", numberOfItems,
            DEFAULT_COLLECTION_NAME);

    long startTime = System.currentTimeMillis();

    for (int i = 0; i < numberOfItems; i++) {

        BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().add("timestamp", new Date())
                .add("field1", "123456").add("field2", "2345678")
                .add("field3", "123123231313131232131231231231123132123123123").add("field4", true);

        WriteResult result = collection.insert(builder.get());
        if (!result.getLastError().ok()) {
            log.error("An error occurred [{}]", result.getLastError());
        }
    }

    long endTime = System.currentTimeMillis();

    log.info("Finished benchmarking.");
    long timeTakenMillis = endTime - startTime;

    float timeTaken = (float) timeTakenMillis / 1000;

    log.info("Results:\n\n" + String.format("%-25s %d", "Number of Items inserted:", numberOfItems) + "\n"
            + String.format("%-25s %.2f", "Time elapsed:", timeTaken) + " seconds\n"
            + String.format("%-25s %.2f", "Throughput:", numberOfItems / timeTaken) + " items/sec\n");

    log.info("Removing test data...");
    collection.remove(new BasicDBObject());
    log.info("Cleared collection [test]");
}

From source file:com.uquetignyadminapp.visual.Admin_NewTable.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    try {// w  w  w.  j  a  v  a  2s  .  c o  m
        ConnectionMongoDB connec = new ConnectionMongoDB();
        DB d = connec.getDB();

        if (cpt == 1) {
            DBCollection coll = d.getCollection(a.getText());

            BasicDBObject doc = new BasicDBObject(jTextField2.getText(), jTextField10.getText())
                    .append(jTextField3.getText(), jTextField11.getText());

            coll.insert(doc);
        }

        if (cpt == 2) {
            DBCollection coll = d.getCollection(a.getText());

            BasicDBObject doc = new BasicDBObject(jTextField2.getText(), jTextField10.getText())
                    .append(jTextField3.getText(), jTextField11.getText())
                    .append(jTextField4.getText(), jTextField12.getText());

            coll.insert(doc);
        }

        if (cpt == 3) {
            DBCollection coll = d.getCollection(a.getText());

            BasicDBObject doc = new BasicDBObject(jTextField2.getText(), jTextField10.getText())
                    .append(jTextField3.getText(), jTextField11.getText())
                    .append(jTextField4.getText(), jTextField12.getText())
                    .append(jTextField5.getText(), jTextField13.getText());

            coll.insert(doc);
        }

        if (cpt == 4) {
            DBCollection coll = d.getCollection(a.getText());

            BasicDBObject doc = new BasicDBObject(jTextField2.getText(), jTextField10.getText())
                    .append(jTextField3.getText(), jTextField11.getText())
                    .append(jTextField4.getText(), jTextField12.getText())
                    .append(jTextField5.getText(), jTextField13.getText())
                    .append(jTextField6.getText(), jTextField14.getText());

            coll.insert(doc);
        }

        if (cpt == 5) {
            DBCollection coll = d.getCollection(a.getText());

            BasicDBObject doc = new BasicDBObject(jTextField2.getText(), jTextField10.getText())
                    .append(jTextField3.getText(), jTextField11.getText())
                    .append(jTextField4.getText(), jTextField12.getText())
                    .append(jTextField5.getText(), jTextField13.getText())
                    .append(jTextField6.getText(), jTextField14.getText())
                    .append(jTextField7.getText(), jTextField15.getText());

            coll.insert(doc);
        }

        if (cpt == 6) {
            DBCollection coll = d.getCollection(a.getText());

            BasicDBObject doc = new BasicDBObject(jTextField2.getText(), jTextField10.getText())
                    .append(jTextField3.getText(), jTextField11.getText())
                    .append(jTextField4.getText(), jTextField12.getText())
                    .append(jTextField5.getText(), jTextField13.getText())
                    .append(jTextField6.getText(), jTextField14.getText())
                    .append(jTextField7.getText(), jTextField15.getText())
                    .append(jTextField8.getText(), jTextField16.getText());

            coll.insert(doc);
        }
        if (cpt == 7) {
            DBCollection coll = d.getCollection(a.getText());

            BasicDBObject doc = new BasicDBObject(jTextField2.getText(), jTextField10.getText())
                    .append(jTextField3.getText(), jTextField11.getText())
                    .append(jTextField4.getText(), jTextField12.getText())
                    .append(jTextField5.getText(), jTextField13.getText())
                    .append(jTextField6.getText(), jTextField14.getText())
                    .append(jTextField7.getText(), jTextField15.getText())
                    .append(jTextField8.getText(), jTextField16.getText())
                    .append(jTextField9.getText(), jTextField17.getText());

            coll.insert(doc);
        }

        javax.swing.JOptionPane.showMessageDialog(null, "La table " + a.getText() + " a bien t cre");

        Admin1 admin = new Admin1();
        admin.setVisible(true);
        this.setVisible(false);

    } catch (UnknownHostException ex) {
        Logger.getLogger(Admin_NewTable.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.uquetignyadminapp.visual.Admin_NewTuples.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    try {/*  w  w  w  . j a  v a2s  .  co m*/
        ConnectionMongoDB connect = new ConnectionMongoDB();
        DB d = connect.getDB();

        if (jLabel2.getText().equals("Campus")) {
            DBCollection coll = d.getCollection(this.jLabel2.getText());

            BasicDBObject doc = new BasicDBObject("_id", jTextField1.getText())
                    .append("site_campus", jTextField2.getText())
                    .append("adresse_campus", jTextField3.getText()).append("telephone", jTextField4.getText())
                    .append("fax", jTextField5.getText()).append("responsable", jTextField6.getText());
            coll.insert(doc);
        }

        if (jLabel2.getText().equals("Personne")) {
            DBCollection coll = d.getCollection(this.jLabel2.getText());

            BasicDBObject doc = new BasicDBObject("_id", jTextField1.getText())
                    .append("type", jTextField2.getText()).append("nompersonne", jTextField3.getText())
                    .append("prenompersonne", jTextField4.getText())
                    .append("titrepersonne", jTextField5.getText())
                    .append("adressepersonne", jTextField6.getText())
                    .append("telephonepersonne", jTextField7.getText())
                    .append("codepostalpersonne", jTextField8.getText())
                    .append("typecours", jTextField9.getText()).append("campusid", jTextField10.getText());
            coll.insert(doc);
        }

        if (jLabel2.getText().equals("Batiment")) {
            DBCollection coll = d.getCollection(this.jLabel2.getText());

            BasicDBObject doc = new BasicDBObject("_id", jTextField1.getText())
                    .append("nombatiment", jTextField2.getText()).append("adresse", jTextField3.getText())
                    .append("telephone", jTextField4.getText()).append("niveau", jTextField5.getText())
                    .append("campusid", jTextField6.getText())
                    .append("telephonepersonne", jTextField7.getText()).append("ufrid", jTextField8.getText());
            coll.insert(doc);
        }

        if (jLabel2.getText().equals("UFR")) {
            DBCollection coll = d.getCollection(this.jLabel2.getText());

            BasicDBObject doc = new BasicDBObject("_id", jTextField1.getText())
                    .append("nomUFR", jTextField2.getText()).append("doyenUFR", jTextField3.getText())
                    .append("typeUFR", jTextField4.getText()).append("departementUFR", jTextField5.getText())
                    .append("centrerechercheUFR", jTextField6.getText())
                    .append("batimentid", jTextField7.getText());
            coll.insert(doc);
        }

        if (jLabel2.getText().equals("Bureau")) {
            DBCollection coll = d.getCollection(this.jLabel2.getText());

            BasicDBObject doc = new BasicDBObject("numerobureau", jTextField1.getText())
                    .append("telephonebureau", jTextField2.getText())
                    .append("batimentid", jTextField3.getText());
            coll.insert(doc);
        }

        if (jLabel2.getText().equals("Classe")) {
            DBCollection coll = d.getCollection(this.jLabel2.getText());

            BasicDBObject doc = new BasicDBObject("numeroclasse", jTextField1.getText())
                    .append("placesclasse", jTextField2.getText()).append("batimentid", jTextField3.getText());
            coll.insert(doc);
        }

        if (jLabel2.getText().equals("LabTP")) {
            DBCollection coll = d.getCollection(this.jLabel2.getText());

            BasicDBObject doc = new BasicDBObject("_id", jTextField1.getText())
                    .append("numerolab", jTextField2.getText()).append("placestp", jTextField3.getText())
                    .append("machinestp", jTextField4.getText()).append("batimentid", jTextField5.getText());
            coll.insert(doc);
        }

        if (jLabel2.getText().equals("CentreRecherche")) {
            DBCollection coll = d.getCollection(this.jLabel2.getText());

            BasicDBObject doc = new BasicDBObject("_id", jTextField1.getText())
                    .append("nomcentrerecherche", jTextField2.getText())
                    .append("directeurcentrerecherche", jTextField3.getText())
                    .append("equipescentrerecherche", jTextField4.getText())
                    .append("UFRid", jTextField5.getText());
            coll.insert(doc);
        }

        if (jLabel2.getText().equals("Departement")) {
            DBCollection coll = d.getCollection(this.jLabel2.getText());

            BasicDBObject doc = new BasicDBObject("_id", jTextField1.getText())
                    .append("nomdepartement", jTextField2.getText())
                    .append("directeurdepartement", jTextField3.getText())
                    .append("profdepartement", jTextField4.getText()).append("UFRid", jTextField5.getText());
            coll.insert(doc);
        }

        if (jLabel2.getText().equals("EcoleInstitut")) {
            DBCollection coll = d.getCollection(this.jLabel2.getText());

            BasicDBObject doc = new BasicDBObject("_id", jTextField1.getText())
                    .append("nomecoleinstitut", jTextField2.getText())
                    .append("directeurecoleinstitut", jTextField3.getText())
                    .append("profecoleinstitut", jTextField4.getText()).append("UFRid", jTextField5.getText());
            coll.insert(doc);
        }

        if (jLabel2.getText().equals("Professeur")) {
            DBCollection coll = d.getCollection(this.jLabel2.getText());

            BasicDBObject doc = new BasicDBObject("_id", jTextField1.getText())
                    .append("nomprofesseur", jTextField2.getText()).append("contact", jTextField3.getText())
                    .append("anne", jTextField4.getText());
            coll.insert(doc);
        }

        if (jLabel2.getText().equals("Cours")) {
            DBCollection coll = d.getCollection(this.jLabel2.getText());

            BasicDBObject doc = new BasicDBObject("_id", jTextField1.getText())
                    .append("nomcours", jTextField2.getText()).append("creditcours", jTextField3.getText())
                    .append("prerequiscours", jTextField4.getText());
            coll.insert(doc);
        }

        if (jLabel2.getText().equals("Diplome")) {
            DBCollection coll = d.getCollection(this.jLabel2.getText());

            BasicDBObject doc = new BasicDBObject("_id", jTextField1.getText())
                    .append("nomdiplome", jTextField2.getText())
                    .append("nbanneesdiplome", jTextField3.getText())
                    .append("prerequis", jTextField4.getText());
            coll.insert(doc);
        }

        javax.swing.JOptionPane.showMessageDialog(null,
                "Des nouvelles donnes ont t insres dans la table :" + " " + jTextField1.getText());

        Admin1 admin = new Admin1();
        admin.setVisible(true);
        this.setVisible(false);

    } catch (UnknownHostException ex) {
        Logger.getLogger(Admin_NewTuples.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.versioneye.persistence.mongodb.GlobalSettingDao.java

public boolean setValue(String environment, String key, String value) throws Exception {
    GlobalSetting gs = new GlobalSetting();
    gs.setEnvironment(environment);//from w  w w .  j a v a  2  s  .co  m
    gs.setKey(key.toUpperCase());
    gs.setValue(value);
    DBCollection globalSettings = getCollection();
    globalSettings.insert(gs.getDBObject());
    return true;
}

From source file:com.versioneye.persistence.mongodb.LicenseDao.java

public void create(License license) {
    DBCollection licenses = getCollection();
    licenses.insert(license.getDBObject());
}

From source file:com.xemsdoom.xeco.core.storage.mongodb.MongoDBStorage.java

License:Open Source License

@Override
public boolean saveAccounts(Set<Account> accounts, Set<String> deleted) {

    Tracker.log("Attempting to save Accounts in MongoDB...");
    long start = System.currentTimeMillis();

    DBCollection coll = db.getCollection(collection);

    // Remove deleted accounts from collection
    for (String acc : deleted) {
        coll.remove(new BasicDBObject("_id", acc));
    }//www  .j  av  a2 s.  c  om

    // Update, Insert
    for (Account acc : accounts) {

        BasicDBObject query = new BasicDBObject("_id", acc.getAccountName());
        DBCursor cursor = coll.find(query);

        // Check if document already exists
        if (cursor.hasNext()) {

            DBObject old = cursor.next();
            BasicDBObject update = new BasicDBObject();

            // Update
            update.put("_id", acc.getAccountName());
            update.put("balance", acc.getBalance());
            update.put("freezed", acc.isFrozen());
            coll.update(old, update);

        } else {

            // Insert
            BasicDBObject insert = new BasicDBObject("_id", acc.getAccountName())
                    .append("balance", acc.getBalance()).append("freezed", acc.isFrozen());
            coll.insert(insert);
        }
    }

    Tracker.log("Saving Accounts in MongoDB took: "
            .concat(String.valueOf((System.currentTimeMillis() - start)).concat("ms.")));
    Tracker.log("Saved " + accounts.size() + " and deleted " + deleted.size() + " Accounts.");
    return true;
}