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:usermanager.Main3.java

private void btnUpdateUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateUserActionPerformed
    // Get connection to the Collection
    DB userDB = DBManager.getDatabase();
    DBCollection col = userDB.getCollection("user");
    // Search//from   ww  w  .java2 s .  c om
    BasicDBObject query = new BasicDBObject();
    query.put("_id", Integer.parseInt(txtId.getText()));
    // Update values
    BasicDBObject doc = new BasicDBObject();
    doc.put("firstName", txtFirstName.getText());
    doc.put("lastName", txtLastName.getText());
    // Update object only with the relevant fields using $set
    BasicDBObject updateObj = new BasicDBObject();
    updateObj.put("$set", doc);
    WriteResult result = col.update(query, updateObj);
}

From source file:v7cr.v7db.Versioning.java

License:Open Source License

/**
 * updates an object, but only if the base version has not been changed in
 * the meantime. The object must have an _id field. The _version field if
 * present is ignored, and set to baseVersion+1.
 *///from ww w  . jav a 2 s  .c om

public static WriteResult update(DBCollection collection, final int baseVersion, DBObject object) {
    object.put(VERSION, baseVersion + 1);
    Object id = object.get("_id");
    WriteResult result = collection.update(new BasicDBObject("_id", id).append(VERSION, baseVersion), object);
    if (result.getN() != 1)
        throw new ConcurrentModificationException("baseVersion has changed");
    return result;
}

From source file:xbdd.webapp.resource.feature.AdminUtils.java

License:Apache License

@DELETE
@Path("/delete/{product}/{version}/{build}")
@Produces("application/json")
public Response softDeleteSingleBuild(@PathParam("product") final String product,
        @PathParam("build") final String build, @PathParam("version") final String version,
        @Context final HttpServletRequest req, @Context final HttpServletResponse response) throws IOException {

    final DB db = this.client.getDB("bdd");
    final DBCollection collection = db.getCollection("summary");
    final DBCollection targetCollection = db.getCollection("deletedSummary");

    final Pattern productReg = java.util.regex.Pattern.compile("^" + product + "/" + version + "$");
    final BasicDBObject query = new BasicDBObject("_id", productReg);

    final DBCursor cursor = collection.find(query);

    while (cursor.hasNext()) {
        DBObject doc = cursor.next();/*from  w  w w  .  j  a  va 2  s  . co  m*/
        DBObject backupDoc = doc;
        //Make sure the backup document only has the deleted build number
        try {
            final String[] singleBuild = { build };
            backupDoc.put("builds", singleBuild);
            targetCollection.insert(backupDoc);
        } catch (DuplicateKeyException e) {
            //The backup document already exists, possibly already deleted a build
            //Lets add the deleted build to the existing document
            targetCollection.update(new BasicDBObject("_id", backupDoc.get("_id")),
                    new BasicDBObject("$push", new BasicDBObject("builds", build)));
        } catch (Exception e) {
            return Response.status(500).build();
        }
        //Remove the build number from the current document and push it back into the collection
        try {
            collection.update(new BasicDBObject("_id", doc.get("_id")),
                    new BasicDBObject("$pull", new BasicDBObject("builds", build)));
        } catch (Exception e) {
            System.out.println(e);
            return Response.status(500).build();
        }
    }
    return Response.ok().build();
}

From source file:xbdd.webapp.resource.feature.AdminUtils.java

License:Apache License

@PUT
@Consumes(MediaType.APPLICATION_JSON)//from  ww  w . j  a  v a  2 s .  com
@Path("/{product}")
@Produces("application/json")
public Response renameProduct(@PathParam("product") final String product, final Product renameObject) {

    final DB db = this.client.getDB("bdd");
    final List<DBCollection> collections = Arrays.asList(db.getCollection("summary"),
            db.getCollection("features"), db.getCollection("reportStats"), db.getCollection("testingTips"));

    final Pattern productReg = Pattern.compile("^" + product + "/");
    final BasicDBObject query = new BasicDBObject("_id", productReg);

    //Before anything lets check the new name isn't already in use

    final BasicDBObject existsQuery = new BasicDBObject("_id", Pattern.compile("^" + renameObject.name + "/"));
    final int summaryCount = db.getCollection("summary").find(existsQuery).count();
    final int delCount = db.getCollection("deletedSummary").find(existsQuery).count();

    if (delCount + summaryCount != 0) {
        throw new WebApplicationException();
    }

    //We need to rename the product everywhere
    //First up are all the collection with the product in the _id attribute
    for (DBCollection collectioni : collections) {
        DBCursor cursor = collectioni.find(query);
        while (cursor.hasNext()) {
            DBObject doc = cursor.next();
            String id = (String) doc.get("_id");
            doc = renameDoc(product, renameObject.name, doc);
            collectioni.insert(doc);
            collectioni.remove(new BasicDBObject("_id", id));
        }
    }

    //Then we deal with the environments collection where only the coordinates.product is set
    final DBCollection[] noIDCollections = { db.getCollection("environments"),
            db.getCollection("deletedSummary") };
    final BasicDBObject enviroQuery = new BasicDBObject("coordinates.product", product);

    for (int i = 0; i < noIDCollections.length; i++) {
        final DBCursor enviroCursor = noIDCollections[i].find(enviroQuery);

        while (enviroCursor.hasNext()) {
            DBObject doc = enviroCursor.next();
            DBObject coordinates = (DBObject) doc.get("coordinates");
            coordinates.put("product", renameObject.name);
            DBObject updateDoc = new BasicDBObject("$set", new BasicDBObject("coordinates", coordinates));
            noIDCollections[i].update(new BasicDBObject("_id", doc.get("_id")), updateDoc);
        }
    }

    //Then we correct the name in any users favourites object
    final DBCollection userCollection = db.getCollection("users");
    final BasicDBObject favouriteQuery = new BasicDBObject("favourites." + product,
            new BasicDBObject("$exists", true));
    final DBCursor users = userCollection.find(favouriteQuery);

    while (users.hasNext()) {
        DBObject doc = users.next();
        DBObject favs = (DBObject) doc.get("favourites");
        favs.put(renameObject.name, favs.get(product));
        BasicDBObject updateDoc = new BasicDBObject("$set", new BasicDBObject("favourites", favs));
        updateDoc.put("$unset", new BasicDBObject(product, ""));
        userCollection.update(new BasicDBObject("_id", doc.get("_id")), updateDoc);
    }

    return Response.ok().build();
}

From source file:xbdd.webapp.resource.feature.BuildReOrdering.java

License:Apache License

@PUT
@Path("/{product}/{major}.{minor}.{servicePack}")
@Consumes("application/json")
public Response setBuildOrderForProductVersion(@BeanParam Coordinates coordinates, final Builds json) {
    final DB db = this.client.getDB("bdd");
    final DBCollection summaryCollection = db.getCollection("summary");
    final BasicDBObject query = new BasicDBObject("_id",
            coordinates.getProduct() + "/" + coordinates.getVersionString());
    summaryCollection.update(query, new BasicDBObject("$set", new BasicDBObject("builds", json.builds)));

    return Response.ok().build();
}

From source file:xbdd.webapp.resource.feature.Favourites.java

License:Apache License

public void setFavouriteStateOfProduct(final String product, final boolean state,
        final HttpServletRequest req) {

    final DB db = this.client.getDB("bdd");
    final DBCollection collection = db.getCollection("users");

    final BasicDBObject user = new BasicDBObject();
    user.put("user_id", req.getRemoteUser());

    final DBObject blank = new BasicDBObject();
    collection.findAndModify(user, blank, blank, false, new BasicDBObject("$set", user), true, true);

    //User exists
    final DBObject favourites = new BasicDBObject("favourites." + product, state);
    final DBObject update = new BasicDBObject("$set", favourites);
    collection.update(user, update);
}

From source file:xbdd.webapp.resource.feature.Favourites.java

License:Apache License

private void setPinStateOfBuild(final String product, final String version, final String build,
        final boolean state) {

    final DB db = this.client.getDB("bdd");
    final DBCollection collection = db.getCollection("summary");

    final BasicDBObject query = new BasicDBObject("_id", product + "/" + version);
    final BasicDBObject toBePinned = new BasicDBObject("pinned", build);
    final String method;

    if (state) {/*from w  w  w .  j a  v  a 2s.c  om*/
        method = "$addToSet";
    } else {
        method = "$pull";
    }

    collection.update(query, new BasicDBObject(method, toBePinned));
}

From source file:xbdd.webapp.resource.feature.Recents.java

License:Apache License

/**
 * Uses the '.+' regexp on featureId to allow for symbols such as slashes in the id
 * /* w w  w .  j a  v  a2 s .co m*/
 * @param String id The featureId to get the history for
 * @return Response Either a 200 response or a 500
 */
@PUT
@Path("/feature/{product}/{major}.{minor}.{servicePack}/{build}/{id:.+}")
@Produces("application/json")
public Response addFeatureToRecents(@QueryParam("name") final String featureName,
        @BeanParam Coordinates coordinates, @PathParam("id") final String featureID,
        @Context final HttpServletRequest req) {

    final BasicDBObject featureDetails = new BasicDBObject("name", featureName);
    featureDetails.put("product", coordinates.getProduct());
    featureDetails.put("version", coordinates.getVersionString());
    featureDetails.put("build", coordinates.getBuild());
    featureDetails.put("id", featureID);

    final DB db = this.client.getDB("bdd");
    final DBCollection collection = db.getCollection("users");

    final BasicDBObject user = new BasicDBObject();
    user.put("user_id", req.getRemoteUser());

    final DBObject blank = new BasicDBObject();
    DBObject doc = collection.findAndModify(user, blank, blank, false, new BasicDBObject("$set", user), true,
            true);

    if (doc.containsField("recentFeatures")) {
        BasicDBList featureArray = (BasicDBList) doc.get("recentFeatures");
        if (featureArray.contains(featureDetails)) {
            featureArray.remove(featureDetails);
            featureArray.add(featureDetails);
            collection.update(user,
                    new BasicDBObject("$set", new BasicDBObject("recentFeatures", featureArray)));
        } else {
            if (featureArray.size() >= 5) {
                collection.update(user, new BasicDBObject("$pop", new BasicDBObject("recentFeatures", "-1")));
            }
            collection.update(user,
                    new BasicDBObject("$addToSet", new BasicDBObject("recentFeatures", featureDetails)));
        }
    } else {
        collection.update(user,
                new BasicDBObject("$addToSet", new BasicDBObject("recentFeatures", featureDetails)));
    }

    return Response.ok().build();
}

From source file:xbdd.webapp.resource.feature.Recents.java

License:Apache License

@PUT
@Path("/build/{product}/{major}.{minor}.{servicePack}/{build}")
@Produces("application/json")
public Response addBuildToRecents(@BeanParam Coordinates coordinates, @Context final HttpServletRequest req) {

    DBObject buildCoords = coordinates.getReportCoordinates();

    final DB db = this.client.getDB("bdd");
    final DBCollection collection = db.getCollection("users");

    final BasicDBObject user = new BasicDBObject();
    user.put("user_id", req.getRemoteUser());

    final DBObject blank = new BasicDBObject();
    DBObject doc = collection.findAndModify(user, blank, blank, false, new BasicDBObject("$set", user), true,
            true);/*from ww w  . ja va2 s  .  c o m*/

    if (doc.containsField("recentBuilds")) {
        BasicDBList buildArray = (BasicDBList) doc.get("recentBuilds");
        if (buildArray.contains(buildCoords)) {
            //BasicDBObject toMove = (BasicDBObject) featureArray.get(featureArray.indexOf(featureDetails));
            buildArray.remove(buildCoords);
            buildArray.add(buildCoords);
            collection.update(user, new BasicDBObject("$set", new BasicDBObject("recentBuilds", buildArray)));
        } else {
            if (buildArray.size() >= 5) {
                collection.update(user, new BasicDBObject("$pop", new BasicDBObject("recentBuilds", "-1")));
            }
            collection.update(user,
                    new BasicDBObject("$addToSet", new BasicDBObject("recentBuilds", buildCoords)));
        }
    } else {
        collection.update(user, new BasicDBObject("$addToSet", new BasicDBObject("recentBuilds", buildCoords)));
    }

    return Response.ok().build();
}