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:Modules.Client.Model.DAO.DAO_Mongo_client.java

public static void insert_Client() {
    DBCollection table = Singleton_app.collection;
    Client_class c = Singleton_client.cl;
    table.insert(c.Client_to_DB());
}

From source file:mongocrud.AddWindow.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:

    Student s = new Student();

    String name = jTextField1.getText().toString();
    String id = jTextField3.getText();
    //        int age1 = Integer.parseInt(jTextField2.getText());

    s.setName(name);/*w w w.j ava2 s. c om*/
    s.setAge(24);
    s.setId(id);

    DBObject dob = create(s);

    DB userDB = DBManager.getDatabase();
    DBCollection col = userDB.getCollection("student");
    WriteResult result = col.insert(dob);

    System.out.println("successfully inserted");
}

From source file:mongodb.JavaDocAdd.java

public static void addSelfie(DBCollection collection) {
    BasicDBObject selfie = new BasicDBObject("word", "selfie");
    selfie.append("first", "s").append("last", "e");
    selfie.append("size", 6).append("category", "New");
    BasicDBObject stats = new BasicDBObject("consonants", 3);
    stats.append("vowels", 3);
    selfie.append("stats", stats);
    selfie.append("letters", new String[] { "s", "e", "l", "f", "i" });
    BasicDBObject cons = new BasicDBObject("type", "consonants");
    cons.append("chars", new String[] { "s", "l", "f" });
    BasicDBObject vowels = new BasicDBObject("type", "vowels");
    vowels.append("chars", new String[] { "e", "i" });
    BasicDBObject[] charsets = new BasicDBObject[] { cons, vowels };
    selfie.append("charsets", charsets);
    WriteResult result = collection.insert(selfie);
    System.out.println("Insert One Result: \n" + result.toString());
}

From source file:mongodb.JavaDocAdd.java

public static void addGoogleAndTweet(DBCollection collection) {
    //Create google Object
    BasicDBObject google = new BasicDBObject("word", "google");
    google.append("first", "g").append("last", "e");
    google.append("size", 6).append("category", "New");
    BasicDBObject stats = new BasicDBObject("consonants", 3);
    stats.append("vowels", 3);
    google.append("stats", stats);
    google.append("letters", new String[] { "g", "o", "l", "e" });
    BasicDBObject cons = new BasicDBObject("type", "consonants");
    cons.append("chars", new String[] { "g", "l" });
    BasicDBObject vowels = new BasicDBObject("type", "vowels");
    vowels.append("chars", new String[] { "o", "e" });
    BasicDBObject[] charsets = new BasicDBObject[] { cons, vowels };
    google.append("charsets", charsets);
    //Create tweet Object
    BasicDBObject tweet = new BasicDBObject("word", "tweet");
    tweet.append("first", "t").append("last", "t");
    tweet.append("size", 6).append("category", "New");
    BasicDBObject tstats = new BasicDBObject("consonants", 3);
    stats.append("vowels", 2);
    tweet.append("stats", tstats);
    tweet.append("letters", new String[] { "t", "w", "e" });
    BasicDBObject tcons = new BasicDBObject("type", "consonants");
    tcons.append("chars", new String[] { "t", "w" });
    BasicDBObject tvowels = new BasicDBObject("type", "vowels");
    tvowels.append("chars", new String[] { "e" });
    BasicDBObject[] tcharsets = new BasicDBObject[] { tcons, tvowels };
    tweet.append("charsets", tcharsets);
    //Insert object array
    WriteResult result = collection.insert(new BasicDBObject[] { google, tweet });
    System.out.println("Insert Multiple Result: \n" + result.toString());
}

From source file:mongodb.Movies_import.java

public static void main(String[] args)
        throws UnknownHostException, MongoException, FileNotFoundException, IOException {

    Mongo mongo = new Mongo(); //creating an instance of mongodb called mongo

    //using mongo object to get the database name
    List<String> databases = mongo.getDatabaseNames();
    for (String string : databases) {
        System.out.println(string);
    }// w w  w.  j  av  a2 s .c  om

    //assigning db variable to mongoDB directory 'db' created in the terminal
    DB db = mongo.getDB("db");

    DBCollection Collection = db.getCollection("movies_import");

    FileReader filereader = null;
    BufferedReader bufferreader = null;

    try {
        filereader = new FileReader("/Users/cheryldsouza/Documents/UPITT/Data Analytics/ml-10M100K/movies.dat");
        bufferreader = new BufferedReader(filereader);
        System.out.println("Mongodb Files");

        String read = bufferreader.readLine();

        while (read != null) {
            System.out.println(read);

            String[] reads = read.split("::");

            BasicDBObject object = new BasicDBObject();

            object.append("MovieID", reads[0]);

            object.append("Title", reads[1]);

            object.append("Genres", reads[2]);

            Collection.insert(object);
            read = bufferreader.readLine();
        }

    } catch (FileNotFoundException e) {
        System.out.println("Documents not found");
        System.exit(-1);
    }

    catch (IOException e) {
        System.out.println("FAILED");
        System.exit(-1);
    }
}

From source file:mongodb.tagsimport.java

public static void main(String[] args) throws UnknownHostException, MongoException {

    Mongo mongo = new Mongo();

    List<String> databases = mongo.getDatabaseNames();
    for (String str : databases) {
        System.out.println(str);//from   w w w  .j a v a 2 s  .  c o  m
    }

    DB db = mongo.getDB("db");

    DBCollection dbCollection = db.getCollection("tags_import");

    FileReader filereader = null;
    BufferedReader bufferreader = null;

    try {
        filereader = new FileReader("/Users/cheryldsouza/Documents/UPITT/Data Analytics/ml-10M100K/tags.dat");
        bufferreader = new BufferedReader(filereader);
        System.out.println("Mongodb Tags File");

        String read = bufferreader.readLine();

        while (read != null) {
            System.out.println(read);

            String[] reads = read.split("::");

            //inserting keys

            BasicDBObject object = new BasicDBObject();

            //UserID::MovieID::Tag::Timestamp

            object.append("UserID", reads[0]);

            object.append("MovieID", reads[1]);

            object.append("Tag", reads[2]);

            object.append("Timestamp", reads[3]);

            dbCollection.insert(object);
            read = bufferreader.readLine();
        }

    } catch (FileNotFoundException e) {
        System.out.println("No documents found. Please try again");
        System.exit(-1);
    }

    catch (IOException e) {
        System.out.println("FAILED");
        System.exit(-1);
    }
}

From source file:mongoHandler.Handler.java

public boolean crearNuevoDocumento(BasicDBObject datos, String nombreColeccion) {
    try {/*  w  w w . j  av  a2s . co m*/
        DBCollection coleccion = dataBase.getCollection(nombreColeccion);
        coleccion.insert(datos);
        System.out.println("DOCUMENTO CREADO");
        return true;
    } catch (Exception e) {
        System.out.println("NO SE PUDO CREAR EL DOCUMENTO : " + e.getMessage());
        return false;
    }
}

From source file:mx.edu.cide.justiciacotidiana.v1.mongo.MongoInterface.java

License:Open Source License

/**
 * Agrega un elemento a una coleccin./* w w  w .j  ava  2  s.com*/
 * @param collectionName Nombre de la coleccin donde se agregar el elemento.
 * @param item Elemento a insertar.
 * @return ID del elemento insertado. null en otro caso.
 */
public String addItem(String collectionName, BasicDBObject item) {
    DBCollection tCol = mongoDB.getCollection(collectionName);
    item.put(FIELD_CREATED, new Date());

    //Eliminar id y updated, si es que viene en el documento.
    item.remove(FIELD_ID);
    item.remove(FIELD_UPDATED);
    try {
        tCol.insert(item);
    } catch (MongoException ex) {
        return null;
    }
    return item.getString(FIELD_ID);
}

From source file:mx.org.cedn.avisosconagua.mongo.MongoInterface.java

License:Open Source License

/**
 * Flags te advice as succesfully generated (completed)
 * @param adviceID ID for the current advice
 * @param previous ID for the previous advice (if any)
 * @param title title of the advice/*from   w w  w  .  java2s . com*/
 * @param type type of the advice. One of pacdp|atldp|pacht|atlht.
 * @param date issue date of the advice
 */
public void setGenerated(String adviceID, String previous, String title, String type, String date) {
    DBCollection col = mongoDB.getCollection(GENERATED_COL);
    String isodate = Utils.getOrderDate(date);
    BasicDBObject nuevo = new BasicDBObject(INTERNAL_FORM_ID, adviceID).append(GENERATED_TITLE, title)
            .append("previousIssue", previous).append("generationTime", Utils.sdf.format(new Date()))
            .append("adviceType", type).append("issueDate", isodate);
    BasicDBObject query = new BasicDBObject(INTERNAL_FORM_ID, adviceID);
    BasicDBObject old = (BasicDBObject) col.findOne(query);
    if (null == old) {
        col.insert(nuevo);
    } else {
        col.update(old, nuevo);
    }
}

From source file:mypackage.CreateDB.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        String getDBName = request.getParameter("dbname");
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        HttpSession httpSession = request.getSession(false);
        DB db = mongoClient.getDB("mydb");
        DBCollection dBCollection = db.getCollection(httpSession.getAttribute("uname") + "DB");
        BasicDBObject dBObject = new BasicDBObject();
        dBObject.put("kapil", getDBName);
        WriteResult writeResult = dBCollection.insert(dBObject);

        if (writeResult.getN() == 0) {
            out.print("true");
            MongoDatabase mongoDatabase = mongoClient.getDatabase(getDBName);
            mongoDatabase.createCollection("Welcome");
            mongoDatabase.drop();/*from  w  w w .j  a  va 2s . c  om*/
        } else {
            out.print("false");
        }

    }
}