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) 

Source Link

Document

Modify an existing document.

Usage

From source file:ch.agent.crnickl.mongodb.WriteMethodsForProperty.java

License:Apache License

/**
 * Update the name of the property./*w  ww.  ja  v a  2s  . c  o  m*/
 * If updating fails throw an exception.
 * 
 * @param prop a property
 * @param policy a schema updating policy
 * @throws T2DBException
 */
public void updateProperty(Property<?> prop, SchemaUpdatePolicy policy) throws T2DBException {
    boolean done = false;
    Throwable cause = null;
    Surrogate s = prop.getSurrogate();
    try {
        check(Permission.MODIFY, prop);
        DBCollection coll = getMongoDB(s).getProperties();
        coll.update(asQuery(s.getId()), operation(Operator.SET, MongoDatabase.FLD_PROP_NAME, prop.getName()));
        done = true;
    } catch (Exception e) {
        cause = e;
    } finally {
    }
    if (!done || cause != null)
        throw T2DBMsg.exception(cause, E.E20116, prop.getName());
}

From source file:co.edu.uniandes.csw.Arquidalgos.usuario.persistence._UsuarioPersistence.java

License:MIT License

public void updateUsuario(UsuarioDTO detail) {
    //      UsuarioEntity entity=entityManager.merge(UsuarioConverter.persistenceDTO2Entity(detail));
    //      UsuarioConverter.entity2PersistenceDTO(entity);

    DBCollection col = null;
    DBObject query = null;//from   w  w  w .  j  a  v a  2 s.  co  m
    BasicDBObject doc = null;
    DBObject update = new BasicDBObject();

    col = db.getCollection("UsuarioDTO");
    String id = ((UsuarioDTO) detail).getFacebookId();
    query = new BasicDBObject("id", id);
    doc = toDoc(detail);

    update.put("$set", doc);
    col.update(query, update);
}

From source file:com.aankam.servlet.MongoCrudServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  ww  . java 2s. c o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    MongoClientURI uri = new MongoClientURI("mongodb://Username:Pasword@ds061721.mongolab.com:61721/cs612");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());

    response.setContentType("text/html;charset=UTF-8");

    String serialNo = request.getParameter("serialNo");
    String name = request.getParameter("name");
    String emailId = request.getParameter("emailId");
    String operation = request.getParameter("operation");

    BasicDBObject customer;
    BasicDBObject updateQuery;
    BasicDBObject deleteQuery;
    BasicDBObject searchQuery;
    DBCollection customersCollection;
    customersCollection = db.getCollection("Customers");
    DBObject searchResult = null;
    boolean flag = false;
    DBCursor cursor;
    switch (operation) {
    case "create":
        customer = new BasicDBObject();
        customer.put("serialNo", serialNo);
        customer.put("name", name);
        customer.put("emailId", emailId);
        customersCollection.insert(customer);
        break;
    case "update":
        updateQuery = new BasicDBObject();
        updateQuery.append("serialNo", serialNo);
        cursor = customersCollection.find(updateQuery);
        customer = new BasicDBObject();
        customer.put("serialNo", serialNo);
        customer.put("name", name);
        customer.put("emailId", emailId);
        if (cursor.hasNext()) {
            customersCollection.update(updateQuery, customer);
            flag = true;
        }

        break;
    case "delete":
        deleteQuery = new BasicDBObject();
        deleteQuery.append("serialNo", serialNo);
        customersCollection.remove(deleteQuery);
        break;
    case "search":
        searchQuery = new BasicDBObject();
        searchQuery.append("serialNo", serialNo);
        cursor = customersCollection.find(searchQuery);
        while (cursor.hasNext()) {
            searchResult = cursor.next();
        }
        break;
    default:
        break;

    }
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet MongoCrudServlet</title>");
        out.println("</head>");
        out.println("<body>");

        switch (operation) {
        case "create":
            out.println("<h3>Customer was successfully created.</h3>");
            break;
        case "update":
            if (flag == true) {
                out.println("<h3>Customer was successfully updated.</h3>");
            } else {
                out.println("<h3>Customer was not found to update.</h3>");
            }

            break;
        case "delete":
            out.println("<h3>Customer was successfully deleted.</h3>");
            break;
        case "search":
            if (searchResult != null) {
                out.println("<h3>The following customer was found:</h3>");
                out.println("<h4>Serial No :" + searchResult.get("serialNo") + "</h4>");
                out.println("<h4>Name :" + searchResult.get("name") + "</h4>");
                out.println("<h4>Email Id :" + searchResult.get("emailId") + "</h4>");
            } else {
                out.println("<h3>Customer not found.</h3>");
            }
            break;
        default:
            break;
        }
        out.println("<a href=\"index.html\">Back to Main Form</a>");
        out.println("</body>");
        out.println("</html>");
    }
}

From source file:com.aperigeek.dropvault.web.dao.MongoFileService.java

License:Open Source License

public Resource mkcol(String username, String resource)
        throws ResourceAlreadyExistsException, ResourceNotFoundException {
    String[] path = resource.split("/");
    Resource parent = getResourceAt(getRootFolder(username), Arrays.copyOfRange(path, 0, path.length - 2));

    if (getChild(parent, path[path.length - 1]) != null) {
        throw new ResourceAlreadyExistsException();
    }//from ww w  . j a v a 2  s. c o m

    DBCollection col = mongo.getDataBase().getCollection("files");

    DBObject obj = new BasicDBObject();
    obj.put("type", Resource.ResourceType.FOLDER.toString());
    obj.put("user", username);
    obj.put("name", path[path.length - 1]);
    obj.put("creationDate", new Date());
    obj.put("modificationDate", new Date());
    obj.put("parent", parent.getId());

    col.insert(obj);

    col.update(new BasicDBObject("_id", parent.getId()),
            new BasicDBObject("$set", new BasicDBObject("modificationDate", new Date())));

    return buildResource(obj);
}

From source file:com.aperigeek.dropvault.web.dao.MongoFileService.java

License:Open Source License

public void put(final String username, String resource, InputStream data, long length, String contentType,
        final char[] password) throws ResourceNotFoundException, IOException {

    final String[] path = resource.split("/");
    Resource parent = getResourceAt(getRootFolder(username), Arrays.copyOfRange(path, 0, path.length - 2));

    DBCollection files = mongo.getDataBase().getCollection("files");
    DBCollection contents = mongo.getDataBase().getCollection("contents");

    ContentDetector contentDetector = null;
    if (contentType == null) {
        PipedInputStream pipeIn = new PipedInputStream();
        PipedOutputStream pipeOut = new PipedOutputStream(pipeIn);
        TeeInputStream tee = new TeeInputStream(data, pipeOut, true);
        contentDetector = new ContentDetector(path[path.length - 1], pipeIn);
        contentDetector.start();/*  w  ww  .  j  a v  a  2  s.  c  o m*/
        data = tee;
    }

    final File dataFile = createDataFile(data, username, password);

    if (contentDetector != null) {
        try {
            contentDetector.join();
            contentType = contentDetector.getContentType();
        } catch (InterruptedException ex) {
            Logger.getLogger(MongoFileService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    Resource child = getChild(parent, path[path.length - 1]);
    if (child != null) {
        DBObject filter = new BasicDBObject();
        filter.put("_id", child.getId());
        DBObject update = new BasicDBObject("modificationDate", new Date());
        update.put("contentLength", length);
        update.put("contentType", contentType);
        files.update(filter, new BasicDBObject("$set", update));

        contents.update(new BasicDBObject("resource", child.getId()),
                new BasicDBObject("$set", new BasicDBObject("file", dataFile.getAbsolutePath())));
    } else {
        DBObject childObj = new BasicDBObject();
        ObjectId objId = new ObjectId();
        childObj.put("_id", objId);
        childObj.put("user", username);
        childObj.put("name", path[path.length - 1]);
        childObj.put("parent", parent.getId());
        childObj.put("type", Resource.ResourceType.FILE.toString());
        childObj.put("creationDate", new Date());
        childObj.put("modificationDate", new Date());
        childObj.put("contentType", contentType);
        childObj.put("contentLength", length);

        files.insert(childObj);

        DBObject content = new BasicDBObject();
        content.put("resource", objId);
        content.put("file", dataFile.getAbsolutePath());

        contents.insert(content);

        files.update(new BasicDBObject("_id", parent.getId()),
                new BasicDBObject("$set", new BasicDBObject("modificationDate", new Date())));

        child = buildResource(childObj);
    }

    final String fContentType = contentType;
    final Resource fChild = child;
    new Thread() {
        public void run() {
            try {
                Map<String, String> metadata = extractionService.extractContent(path[path.length - 1],
                        readFile(dataFile, username, password), fContentType);

                metadata.put("name", path[path.length - 1]);

                indexService.remove(username, new String(password), fChild.getId().toString());
                indexService.index(username, new String(password), fChild.getId().toString(), metadata);
            } catch (Exception ex) {
                Logger.getLogger(MongoFileService.class.getName()).log(Level.SEVERE,
                        "Index failed for " + path[path.length - 1], ex);
            }
        }
    }.start();
}

From source file:com.aperigeek.dropvault.web.dao.MongoFileService.java

License:Open Source License

public void move(String username, Resource source, String dest) throws ResourceNotFoundException {
    String[] path = dest.split("/");
    Resource parent = getRootFolder(username);
    for (int i = 0; i < path.length - 1; i++) {
        parent = getChild(parent, path[i]);
        if (parent == null) {
            throw new ResourceNotFoundException();
        }//from  w w  w  .  jav a2  s  . c om
    }

    DBCollection files = mongo.getDataBase().getCollection("files");

    DBObject update = new BasicDBObject("$set", new BasicDBObjectBuilder().append("parent", parent.getId())
            .append("name", path[path.length - 1]).get());

    DBObject filter = new BasicDBObject("_id", source.getId());

    DBObject current = files.findOne(filter);
    files.update(new BasicDBObject("_id", (ObjectId) current.get("parent")),
            new BasicDBObject("$set", new BasicDBObject("modificationDate", new Date())));

    files.update(filter, update);

    files.update(new BasicDBObject("_id", parent.getId()),
            new BasicDBObject("$set", new BasicDBObject("modificationDate", new Date())));
}

From source file:com.aperigeek.dropvault.web.dao.MongoFileService.java

License:Open Source License

public void delete(String username, String password, Resource resource) {
    DBCollection files = mongo.getDataBase().getCollection("files");
    DBCollection contents = mongo.getDataBase().getCollection("contents");

    for (Resource child : getChildren(resource)) {
        delete(username, password, child);
    }/*from w w  w . j  a v  a2s .  co m*/

    DBObject filter = new BasicDBObject("_id", resource.getId());

    DBObject current = files.findOne(filter);
    files.update(new BasicDBObject("_id", (ObjectId) current.get("parent")),
            new BasicDBObject("$set", new BasicDBObject("modificationDate", new Date())));

    files.remove(filter);
    contents.remove(new BasicDBObject("resource", resource.getId()));

    try {
        indexService.remove(username, password, resource.getId().toString());
    } catch (IndexException ex) {
        Logger.getLogger(MongoFileService.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.app.mongoDao.MongoBookDao.java

@Override
public String updateBook(Book book, String updatedbook) {
    String status = "";
    try {//  w  w  w  . j a  v  a  2  s .co m
        DBCollection data = DatabaseConfig.configure();
        BasicDBObject updateQuery = new BasicDBObject("bookname", updatedbook);
        BasicDBObject updated = new BasicDBObject();
        updated.put("bookname", book.getBookname());
        updated.put("author", book.getAuthor());
        data.update(updateQuery, new BasicDBObject("$set", updated));
        status = "Book updated successfully";
    } catch (Exception e) {
        status = "Book not updated successfully";
        e.printStackTrace();
    }

    return status;

}

From source file:com.avanza.ymer.MirrorEnvironment.java

License:Apache License

public void removeFormatVersion(Class<?> dataType, Object id) {
    String collectionName = dataType.getSimpleName().substring(0, 1).toLowerCase()
            + dataType.getSimpleName().substring(1);
    DBCollection collection = getMongoDb().getCollection(collectionName);
    DBObject idQuery = BasicDBObjectBuilder.start("_id", id).get();
    DBCursor cursor = collection.find(idQuery);

    cursor.next();/* w  w w .  ja  v  a 2 s .c  o m*/
    DBObject obj = cursor.curr();
    cursor.close();

    obj.removeField("_formatVersion");
    collection.update(idQuery, obj);
}

From source file:com.aw.util.MongoDbUtil.java

public static WriteResult updateCollection(String collectionName, DBObject query, DBObject updateObject) {
    DBCollection table = getCollection(defaultDBName, collectionName);
    return table.update(query, updateObject);
}