Example usage for com.mongodb DBCollection update

List of usage examples for com.mongodb DBCollection update

Introduction

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

Prototype

public WriteResult update(final DBObject query, final DBObject update, final boolean upsert,
        final boolean multi) 

Source Link

Document

Modify an existing document or documents in collection.

Usage

From source file:github.macrohuang.orm.mongo.core.MongoDBTemplate.java

License:Apache License

/**
 * Update all the match documents, set their values to the same as the given
 * entry. Note that, the <code>null</code> value of the entry is omitted.
 * You can manual specify the upsert and the multi value.
 * //from   w w  w .  j a  v  a2 s  . co  m
 * @see DBCollection#update(DBObject, DBObject, boolean, boolean)
 * @param <T>
 * @param dbChooser
 * @param query
 * @param entry
 * @param upsert
 * @param multi
 * @return
 */
public <T> boolean update(DBChooser dbChooser, Query query, T entry, boolean upsert, boolean multi) {
    Assert.assertNotNull(query);
    Assert.assertNotNull(dbChooser);
    if (Constants.coreLogEnable)
        LOGGER.info("update:" + dbChooser + ",query:" + query + ",entry:" + entry + ",upsert:" + upsert
                + ",multi:" + multi);
    DBCollection collection = getCollection(dbChooser);
    return isOperateSuccess(collection.update(query.buildQuery(),
            new BasicDBObject("$set", DBObjectUtil.convertPO2DBObject(entry)), upsert, multi));
}

From source file:gov.wa.wsdot.cms.App.java

License:Open Source License

/**
 * Save the channel structure to the database
 * //from  w  w  w.j  a v  a  2s. co  m
 * @param parentReferences
 * @param collection
 */
private static void saveChannels(List<ChannelsAndPostingsBase> parentReferences, DBCollection collection) {

    // Store POJO to MongoDB collection. 
    for (ChannelsAndPostingsBase item : parentReferences) {
        BasicDBObject doc = new BasicDBObject();
        doc.put("uid", item.getUid());
        doc.put("guid", item.getGuid());
        doc.put("name", item.getName());
        doc.put("parent", item.getParent());
        doc.put("level", item.getLevel());
        doc.put("location", item.getLocation());
        doc.put("isChannel", item.getIsChannel());
        doc.put("created", new Date());

        BasicDBObject updateQuery = new BasicDBObject("uid", item.getUid());
        collection.update(updateQuery, doc, true, false);
    }

    System.out.println();
    System.out.println("All done saving channels.");
    System.out.println();
}

From source file:gov.wa.wsdot.cms.App.java

License:Open Source License

/**
 * Save the posting structure and content to the database
 * /* www.  ja va 2 s  .c  o m*/
 * @param postingsHashMap
 * @param collection
 */
private static void savePostings(HashMap<String, ChannelsAndPostingsBase> postingsHashMap,
        DBCollection collection) {

    for (Entry<String, ChannelsAndPostingsBase> entry : postingsHashMap.entrySet()) {
        BasicDBObject doc = new BasicDBObject();
        doc.put("uid", entry.getValue().getUid());
        doc.put("guid", entry.getValue().getGuid());
        doc.put("name", entry.getValue().getName());
        doc.put("parent", entry.getValue().getParent());
        doc.put("level", entry.getValue().getLevel());
        doc.put("location", entry.getValue().getLocation());
        doc.put("isChannel", entry.getValue().getIsChannel());
        doc.put("created", new Date());

        if (entry.getValue().getPageName() != null) {
            doc.put("pageName", entry.getValue().getPageName());
        }

        BasicDBObject updateQuery = new BasicDBObject("uid", entry.getValue().getUid());
        collection.update(updateQuery, doc, true, false);
    }

    System.out.println("All done saving postings.");
}

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 update(String dbName, String colName, DBObject findObj, Object obj) throws Exception {
    DB db = mongoClient.getDB(dbName);/*  w ww  . ja va 2 s  .  c o m*/
    DBCollection coll = db.getCollection(colName);
    BasicDBObject record = new BasicDBObject(BeanUtilEx.transBean2Map(obj));
    coll.update(findObj, new BasicDBObject("$set", record), false, true);
}

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

public void update(String dbName, String colName, DBObject findObj, Map map) throws Exception {
    DB db = mongoClient.getDB(dbName);/*from  w  w  w .  j a  va2 s  .co  m*/
    DBCollection coll = db.getCollection(colName);
    BasicDBObject record = new BasicDBObject(map);
    coll.update(findObj, new BasicDBObject("$set", record), false, true);
}

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

public void update(String dbName, String colName, DBObject findObj, DBObject record) throws Exception {
    DB db = mongoClient.getDB(dbName);/*from   www. jav a  2  s  .  c  om*/
    DBCollection coll = db.getCollection(colName);
    coll.update(findObj, record, false, true);
}

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

public void update(String dbName, String colName, String findJson, String json) {
    DB db = mongoClient.getDB(dbName);/* w w w.j  a v a 2 s .  c o m*/
    DBCollection coll = db.getCollection(colName);
    BasicBSONObject locateObj = (BasicBSONObject) JSON.parse(findJson, new DefaultDBCallback(coll));
    BasicDBObject locate = new BasicDBObject(locateObj);
    BasicBSONObject obj = (BasicBSONObject) JSON.parse(json, new DefaultDBCallback(coll));
    BasicDBObject record = new BasicDBObject(obj);
    coll.update(locate, record, false, true);
}

From source file:mongocrud.UpdateWindow.java

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

    try {//from  ww w.  ja v a2  s.  co m
        DB userDB = DBManager.getDatabase();
        DBCollection col = userDB.getCollection("student");

        BasicDBObject query = new BasicDBObject("_id", new BasicDBObject("$eq", jTextField1.getText()));

        BasicDBObject newDocument = new BasicDBObject();
        newDocument.put("_id", jTextField1.getText());
        newDocument.put("name", jTextField2.getText());
        newDocument.put("age", jTextField3.getText());

        BasicDBObject updateObj = new BasicDBObject();
        updateObj.put("$set", newDocument);

        col.update(query, updateObj, false, true);

        JOptionPane.showMessageDialog(rootPane, "User Update SucessFully...!");

    } catch (Exception e) {
    }

}

From source file:mongodb.JavaDocUpdate.java

public static void updateDoc(DBCollection collection) {
    BasicDBObject query = new BasicDBObject("word", "left");
    BasicDBObject update = new BasicDBObject();
    update.append("$set", new BasicDBObject("word", "lefty"));
    BasicDBObject inc = new BasicDBObject("size", 1);
    inc.append("stats.consonants", 1);
    update.append("$inc", inc);
    update.append("$push", new BasicDBObject("letters", "y"));
    WriteResult result = collection.update(query, update, false, false);
    System.out.println("Update Result: \n" + result.toString());
}