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:integration.util.mongodb.MongodbSeed.java

License:Open Source License

public void loadDataset(URL dbPath, String nodeId) throws IOException {
    Map<String, List<DBObject>> collections = parseDatabaseDump(dbPath);
    collections = updateNodeIdFirstNode(collections, nodeId);
    collections = updateNodeIdInputs(collections, nodeId);

    for (Map.Entry<String, List<DBObject>> collection : collections.entrySet()) {
        final String collectionName = collection.getKey();
        if (mongoDatabase.getCollection(collectionName) == null) {
            mongoDatabase.createCollection(collectionName, new BasicDBObject());
        }/* w  w w  .  j  a  va  2 s.c  om*/
        final DBCollection mongoCollection = mongoDatabase.getCollection(collectionName);

        if (!collection.getValue().isEmpty()) {
            mongoCollection.insert(collection.getValue());
        }
    }
}

From source file:io.github.apfelcreme.LitePortals.Bungee.Database.MongoController.java

License:Open Source License

/**
 * saves a portal//w  w w .j  av  a 2  s.c om
 *
 * @param portal a portal
 */
public void savePortal(Portal portal) {
    DBCollection collection = MongoConnector.getInstance().getCollection();
    BasicDBObject portalObject = new BasicDBObject();
    portalObject.put("portal_id", portal.getId().toString());
    portalObject.put("server", portal.getLocation().getServer());
    portalObject.put("builder", portal.getBuilder().toString());
    portalObject.put("name", portal.getName());
    portalObject.put("enabled", portal.isEnabled());
    portalObject.put("locked", portal.isLocked());
    portalObject.put("world", portal.getLocation().getWorld());
    portalObject.put("loc_x", portal.getLocation().getX());
    portalObject.put("loc_y", portal.getLocation().getY());
    portalObject.put("loc_z", portal.getLocation().getZ());
    portalObject.put("yaw", portal.getLocation().getYaw());
    if (portal.getTarget() != null) {
        portalObject.put("target", portal.getTarget().toString());
    }
    collection.insert(portalObject);

    PortalManager.getInstance().getPortals().add(portal);
}

From source file:io.liveoak.mongo.gridfs.GridFSDirectoryResource.java

License:Open Source License

@Override
public Resource member(RequestContext ctx, String id) {

    GridFSResourcePath childPath = path().append(id);

    if (childPath.equals(ctx.resourcePath())) {

        // there are no more intermediary segments - this is the last parent,
        // here we lookup / generate the target GridFS file

        LinkedList<ResourcePath.Segment> segments = new LinkedList(ctx.resourcePath().segments());
        // skip app
        segments.removeFirst();/*from  w  w  w  .j ava2  s.  c o  m*/
        // skip gridfsroot
        segments.removeFirst();
        // init meta
        boolean meta = segments.getLast().matrixParameters().containsKey("meta");

        DBCollection col = getUserspace().getFilesCollection();

        DBObject result = null;
        GridFSDBObject last = null;
        int count = 0;
        for (ResourcePath.Segment segment : segments) {
            count++;

            // first segment represents root - root file has empty string for a name, and null parent
            String name = count == 1 ? "" : segment.name();
            ObjectId parentId = count == 1 ? null : last.getId();

            result = col.findOne(new BasicDBObject("filename", name).append("parent", parentId));
            if (result == null) {
                if (ctx.requestType() == RequestType.UPDATE) {
                    // create fileInfo for current segment
                    BasicDBObject fileInfo = new BasicDBObject("filename", name).append("owner",
                            ctx.securityContext().getSubject());
                    if (last != null) {
                        fileInfo.append("parent", last.getId());
                    }

                    // insert for directories but not for files
                    // files get inserted via GridFS API in GridFSBlobResource
                    if (count < segments.size()) {
                        fileInfo.append("dir", true);
                        // autocreate missing parent directories when putting a blob
                        col.insert(fileInfo);
                    }
                    result = fileInfo;
                } else {
                    return null;
                }
            }
            last = new GridFSDBObject(result);
        }

        // finally we got to the fileInfo representing the target resource
        if (last.isTrue("dir")) {
            // if target resource represents a directory
            return newChildDir(path(), last);
        } else {
            // if file
            if (meta) {
                // if last segment has matrix parameter 'meta' return meta info instead of blob content
                return newChildItem(last);
            } else {
                // if no ;meta, then return a blob
                return new GridFSBlobResource(ctx, this, id, last, childPath);
            }
        }
    } else if (childPath.segments().size() == ctx.resourcePath().segments().size()) {
        return null;
    } else {
        // pass-through segment
        return new GridFSDirectoryResource(ctx, this, id, childPath);
    }
}

From source file:jahspotify.storage.statistics.MongoDBHistoricalStorage.java

License:Apache License

@Override
public void addHistory(final TrackHistory trackHistory) {
    final DBCollection history = _db.getCollection("history");
    final BasicDBObject basicDBObject = (BasicDBObject) JSON.parse(new Gson().toJson(trackHistory));
    final WriteResult insert = history.insert(basicDBObject);
}

From source file:javaapplication1.InsertUser.java

public static void main(String[] args) {

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

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

    DBCollection user = db.getCollection("User");
    Document d = new Document();
    d.put("Name", new Document().append("First Name", "Akshay").append("Last Name", "Chandila"));
    d.put("Email", "akki@gmail.com");
    d.put("Interests", "Computer Science");
    d.put("Password", "shaolinp");
    d.put("Security Question", "a?");
    d.put("Security Answer", "b");
    DBObject ob = new BasicDBObject(d);
    user.insert(ob);

    DBObject ob1 = new BasicDBObject(new Document("Password", "shaolinp"));
    DBObject ob2 = new BasicDBObject(new Document("$set", new Document("Security Answer", "Akshay1234")));
    user.update(ob1, ob2);/*from  ww w.j a  v a 2 s.  c  om*/
    String tm = "shaolghjmkl;inp";
    DBObject ob3 = new BasicDBObject(new Document("Password", tm));
    DBCursor c2 = user.find(ob3);
    System.out.println(c2.count());
}

From source file:javaapplication15.JavaApplication15.java

/**
 * @param args the command line arguments
 * @throws java.net.UnknownHostException
 *//*from  www.j ava  2s.  c o m*/
public static void main(String[] args) throws UnknownHostException {

    MongoClient client = new MongoClient("localhost", 27017);
    DB myDB = client.getDB("m101");
    DBCollection collection = myDB.getCollection("Sample2");

    collection.drop();

    BasicDBObject query = new BasicDBObject("x", new BasicDBObject("$gt", 10).append("$lt", 50)).append("y",
            new BasicDBObject("$gt", 10).append("$lt", 50));

    for (int i = 0; i < 10; i++) {
        collection.insert(
                new BasicDBObject("x", new Random().nextInt(100)).append("y", new Random().nextInt(100)));
    }

    //        DBObject one = collection.findOne(query);
    //        System.out.println(one);

    DBCursor cursor = collection.find(query);
    try {
        while (cursor.hasNext()) {
            DBObject dBObject = cursor.next();
            System.out.println(dBObject);
        }
    } finally {
        cursor.close();
    }

}

From source file:juan.Estructuraimagen.java

public void intoMongo(ArrayList<ImageMongo> imagesMongo) throws UnknownHostException {

    int imheight = 0;
    int imwidth = 0;
    String immake = "";
    int imdatetime = 0;
    int tamano = 0;
    //conectamos a la base de datos       
    MongoClient mongoClient;//from   w w  w.j ava  2  s.  c  o m

    mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("mydb");
    //BORRAMOS LA BASE DE DATOS PARA QUE NO HAYA ELEMENTOS DUPLICADOS
    db.dropDatabase();

    DBCollection modfecha = db.getCollection("modelo-fecha");
    DBCollection modtam = db.getCollection("modelo-tamao");
    DBCollection modres = db.getCollection("modelo-resolucion");
    DBCollection tamfecha = db.getCollection("tamano-fecha");

    //recuperamos imagenes
    Iterator<ImageMongo> nombreIterator = imagesMongo.iterator();
    BasicDBObject docmf1;
    BasicDBObject docmt1;
    BasicDBObject docmr1;
    BasicDBObject doctf1;
    while (nombreIterator.hasNext()) {

        ImageMongo elem = nombreIterator.next();

        if (elem.getTags() != null) {
            Iterator<Itag> nombreItag = elem.getTags().iterator();
            imheight = 0;
            imwidth = 0;
            immake = "";
            imdatetime = 0;

            while (nombreItag.hasNext()) {
                Itag elemtag = nombreItag.next();

                switch (elemtag.getName()) {
                case "Image Height":
                    imheight = Integer.parseInt(elemtag.getValue());

                    break;
                case "Image Width":
                    imwidth = Integer.parseInt(elemtag.getValue());

                    break;
                case "Make":
                    immake = elemtag.getValue();

                    break;
                case "Date/Time":
                    imdatetime = Integer.parseInt(elemtag.getValue());

                    break;

                }

            }
            tamano = Integer.parseInt(elem.getSize());
            //insertamos un docuemnto en la coleccion
            docmf1 = new BasicDBObject();

            docmf1.put("nombre", elem.getName());
            docmf1.put("fecha", imdatetime);
            docmf1.put("ruta", elem.getRute().getName());
            docmf1.put("marca", immake);
            modfecha.insert(docmf1);

            docmt1 = new BasicDBObject();

            docmt1.put("nombre", elem.getName());
            docmt1.put("tamano", tamano);
            docmt1.put("ruta", elem.getRute().getName());
            docmt1.put("marca", immake);
            modtam.insert(docmt1);

            docmr1 = new BasicDBObject();
            docmr1.put("nombre", elem.getName());
            docmr1.put("height", imheight);
            docmr1.put("width", imwidth);
            docmr1.put("ruta", elem.getRute().getName());
            docmr1.put("marca", immake);
            modres.insert(docmr1);

            doctf1 = new BasicDBObject();
            doctf1.put("nombre", elem.getName());
            doctf1.put("fecha", imdatetime);
            doctf1.put("ruta", elem.getRute().getName());
            doctf1.put("tamano", tamano);
            tamfecha.insert(doctf1);

        }
    }

}

From source file:laboratorio_2_sd.Laboratorio_2_SD.java

public static void main(String[] args) throws Exception {

    //archivo de configuracion
    File archivo = new File("config.ini");
    FileReader fr = new FileReader(archivo);
    BufferedReader br = new BufferedReader(fr);
    String linea = br.readLine();
    int cantParticiones = Integer.parseInt(linea);
    linea = br.readLine();//from  w w w  . jav  a 2  s  .  c  o m
    String[] data = linea.split("\n");
    String rutaDocumentos = data[0];
    linea = br.readLine();
    data = linea.split("\n");
    String rutaStopwords = data[0];
    if (imprime)
        System.out.println("Se configura con:\n- Particiones: " + cantParticiones + "\n- Ruta Documentos: '"
                + rutaDocumentos + "'\n- Ruta StopWords: '" + rutaStopwords + "'\n");

    //Archivo stopwords
    File archivo3 = new File(rutaStopwords);
    FileReader fr3 = new FileReader(archivo3);
    BufferedReader br3 = new BufferedReader(fr3);
    ArrayList<String> stopwords = new ArrayList<>();
    if (imprime) {
        System.out.println("StopWords: \n");
        int contador = 0;
        while ((linea = br3.readLine()) != null && linea.length() != 0) {//mientras no sea EOF
            stopwords.add(linea);
            if (contador < 9) {
                System.out.print(linea + " ");
                contador++;
            } else if (contador == 9) {
                contador = 0;
                System.out.println(linea);
            }
        }
        System.out.println("");
    }
    //Crea db y tablas
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    mongoClient.dropDatabase("indexDB");
    DB db = mongoClient.getDB("indexDB");
    mongoClient.setWriteConcern(WriteConcern.JOURNALED);
    db.setWriteConcern(WriteConcern.JOURNALED);

    DBCollection colDocumentos = db.getCollection("Documentos");
    DBCollection colIndiceInvertido = db.getCollection("IndiceInvertido");
    DBCollection colVocabulario = db.getCollection("Vocabulario");

    colDocumentos.createIndex(new BasicDBObject("idDoc", 1));
    colIndiceInvertido.createIndex(new BasicDBObject("idPalabra", 1));
    colVocabulario.createIndex(new BasicDBObject("palabra", 1));

    //Archivo de documentos
    File archivo2 = new File(rutaDocumentos);
    FileReader fr2 = new FileReader(archivo2);
    BufferedReader br2 = new BufferedReader(fr2);

    int idDoc = 0;
    int idPalabraActual = 0;

    while ((linea = br2.readLine()) != null && !linea.contains("</mediawiki>")) {//mientras no sea EOF

        while (!linea.contains("<page>")) {
            linea = br2.readLine();
        }
        //guarda el titulo
        linea = br2.readLine();
        int indice = linea.indexOf(">");
        String sub = linea.substring(indice + 1);
        indice = sub.indexOf("<");
        String titulo = sub.substring(0, indice);

        //guarda el username
        while (!linea.contains("<username>")) {
            linea = br2.readLine();
        }
        indice = linea.indexOf(">");
        sub = linea.substring(indice + 1);
        indice = sub.indexOf("<");
        String username = sub.substring(0, indice);

        while (linea.contains("<text") == false) {
            linea = br2.readLine();
        }

        //Aqui comienza a leer el contenido del documento
        ArrayList<String> palabrasTemp = new ArrayList<String>();

        while (linea.contains("</text>") == false) {

            linea = br2.readLine();

            if (!linea.contains("</text>")) {
                StringTokenizer st = new StringTokenizer(linea, " #%_-*.,;:|/\\(){}[]=&+'\"?!");
                while (st.hasMoreTokens()) {
                    String palabra = st.nextToken();
                    palabra = palabra.toLowerCase();
                    if (palabra.length() > 1 && !stopwords.contains(palabra)) {
                        palabrasTemp.add(palabra);
                    }
                }
            }

        }
        Documento docTemp = new Documento(idDoc, palabrasTemp, titulo, username);
        if (imprime)
            docTemp.print();
        //Se agrega el documento directamente a la coleccion documentos
        colDocumentos.insert(docTemp.toDBObject());

        for (int i = 0; i < docTemp.cantPalabras; i++) {

            String palabra = docTemp.palabras.get(i);
            if (imprime)
                System.out.println("***********************");
            if (imprime)
                System.out.println("Palabra: " + palabra);
            //revisa si la palabra esta en la coleccion vocabulario
            DBCursor cursor = colVocabulario.find((DBObject) new BasicDBObject("palabra", palabra));
            if (cursor.hasNext()) { //si esta
                if (imprime)
                    System.out.println("Esta en vocabulario");
                Vocabulario vocTemp = new Vocabulario((BasicDBObject) cursor.next());
                if (imprime)
                    System.out.println("idPalabra: " + vocTemp.idPalabra);
                DBCursor cursor2 = colIndiceInvertido
                        .find((DBObject) new BasicDBObject("idPalabra", vocTemp.idPalabra));
                BasicDBObject find = (BasicDBObject) cursor2.next();
                IndiceInvertido indiceTemp = new IndiceInvertido(find);
                //revisa si ya est ingresado el documento actual en el indiceInvertido
                int contador = 0;
                int frec = 0;
                for (int j = 0; j < indiceTemp.frecuencias.size(); j++) {
                    if (indiceTemp.frecuencias.get(j).idDocumento == idDoc) {
                        contador = 1;
                        frec = indiceTemp.frecuencias.get(j).frecuencia;
                        break;
                    }
                }
                if (contador == 1) { //si encontro el id del documento actual
                    if (imprime)
                        System.out.println("Esta en indice invertido");
                    //actualizar frecuencia en indice Invertido
                    indiceTemp.ActualizarFrecuencias(frec + 1, idDoc);
                    colIndiceInvertido.update(find, indiceTemp.toDBObject(), false, true);
                    if (imprime)
                        indiceTemp.print();
                } else {//si no est
                    if (imprime)
                        System.out.println("No est en indice invertido");
                    //actualizar la cantidad de documentos del vocabulario
                    vocTemp.cantDocumentos++;
                    colVocabulario.insert(vocTemp.toDBObject());
                    if (imprime)
                        vocTemp.print();
                    //agregar nueva tupla de frecuencia/idDoc a indice
                    indiceTemp.ActualizarFrecuencias(1, idDoc);
                    if (imprime)
                        indiceTemp.print();
                    colIndiceInvertido.insert(indiceTemp.toDBObject());

                }
            } else {//no esta
                if (imprime)
                    System.out.println("No esta en vocabulario\nInserta nuevo elemento");
                if (idDoc == 0 && i == 0) { //no se ha insertado ningun dato
                    //inserta palabra en vocabulario
                    Vocabulario vocTemp = new Vocabulario(palabra, 0, 1);
                    colVocabulario.insert(vocTemp.toDBObject());
                    if (imprime)
                        vocTemp.print();
                    //inserta entrada en indice invertido
                    IndiceInvertido indiceTemp = new IndiceInvertido(vocTemp.idPalabra, 1, idDoc);
                    colIndiceInvertido.insert(indiceTemp.toDBObject());
                    if (imprime)
                        indiceTemp.print();
                    idPalabraActual++;
                } else {
                    //se obtiene un nuevo id
                    //se inserta a vocabulario
                    Vocabulario vocTemp = new Vocabulario(palabra, idPalabraActual, 1);
                    colVocabulario.insert(vocTemp.toDBObject());
                    if (imprime)
                        vocTemp.print();
                    //se inserta a indice invertido
                    IndiceInvertido indiceTemp = new IndiceInvertido(vocTemp.idPalabra, 1, idDoc);
                    if (imprime)
                        indiceTemp.print();
                    colIndiceInvertido.insert(indiceTemp.toDBObject());
                    idPalabraActual++;
                }
            }
        }

        idDoc++;
        while (!linea.contains("</page>")) {
            linea = br2.readLine();
        }
        pasarGarbageCollector();
    }

}

From source file:me.yyam.mongodbutils.MongoDbOperater.java

public void insert(String dbName, String colName, Map map) {
    DB db = mongoClient.getDB(dbName);//  ww w.  j  a  v a2s.c  om
    DBCollection coll = db.getCollection(colName);
    BasicDBObject record = new BasicDBObject(map);
    coll.insert(record);
}

From source file:me.yyam.mongodbutils.MongoDbOperater.java

public void insert(String dbName, String colName, String json) {
    DB db = mongoClient.getDB(dbName);/*from  w  w  w  .j a  v  a2 s .c om*/
    DBCollection coll = db.getCollection(colName);
    BasicBSONObject obj = (BasicBSONObject) JSON.parse(json, new DefaultDBCallback(coll));
    BasicDBObject record = new BasicDBObject(obj);
    coll.insert(record);
}