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, final WriteConcern aWriteConcern) 

Source Link

Document

Modify an existing document or documents in collection.

Usage

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
/**//  w w w  .  ja va 2 s  .c o m
 * Insert a record in the database. Any field/value pairs in the specified values HashMap will be written into the record with the specified
 * record key.
 *
 * @param entitySet The name of the table
 * @param entityPK The record key of the record to insert.
 * @param values A HashMap of field/value pairs to insert in the record
 * @return Zero on success, a non-zero error code on error. See this class's description for a discussion of error codes.
 */
public int insertEntity(String entitySet, String entityPK, HashMap<String, ByteIterator> values,
        boolean insertImage) {
    com.mongodb.DB db = null;
    WriteResult res = null;
    try {
        // get the appropriate database
        db = mongo.getDB(database);
        // ensure order
        db.requestStart();
        // appropriate table - collection
        DBCollection collection = db.getCollection(entitySet);
        // create the row-object-document
        // need to insert key as integer else the sorting based on id for
        // topk s wont happen properly

        DBObject r = new BasicDBObject().append("_id", Integer.parseInt(entityPK));
        for (String k : values.keySet()) {
            if (!(k.toString().equalsIgnoreCase("pic") || k.toString().equalsIgnoreCase("tpic")))
                r.put(k, values.get(k).toString());
        }

        if (entitySet.equalsIgnoreCase("users")) {
            // ArrayList x = new ArrayList();
            r.put("ConfFriends", new ArrayList<Integer>());
            r.put("PendFriends", new ArrayList<Integer>());
            r.put("wallResources", new ArrayList<Integer>());
        }

        if (entitySet.equalsIgnoreCase("users") && insertImage) {
            // insert picture separately
            // create one gridFS for the datastore
            byte[] profileImage = ((ObjectByteIterator) values.get("pic")).toArray();
            r.put("pic", profileImage);
            // create the thumbnail image
            /*
             * File file = new File("mypic.jpg"); byte fileContent[] = null;
             * try{ //create FileInputStream object FileInputStream fin =
             * new FileInputStream(file); fileContent = new
             * byte[(int)file.length()]; fin.read(fileContent);
             * }catch(Exception e){ e.printStackTrace(); } byte[] thumbImage
             * = fileContent;
             */

            byte[] thumbImage = ((ObjectByteIterator) values.get("tpic")).toArray();
            r.put("tpic", thumbImage);

        }

        res = collection.insert(r, writeConcern);

        if (entitySet.equalsIgnoreCase("resources")) {
            // add the rid to the walluserids profile
            collection = db.getCollection("users");
            DBObject q = new BasicDBObject().append("_id", Integer.parseInt((String) r.get("walluserid")));
            DBObject queryResult = null;
            queryResult = collection.findOne(q);
            String x = queryResult.get("wallResources").toString();
            BasicDBObject updateCommand = new BasicDBObject();
            if (!x.equals("[ ]")) {
                x = x.substring(1, x.length() - 1);
                String resourceIds[] = x.split(",");
                int[] resIds = new int[resourceIds.length + 1];
                for (int i = 0; i < resourceIds.length; i++) { // to limit
                    // it
                    resIds[i] = Integer.parseInt(resourceIds[i].trim());
                }
                resIds[resourceIds.length] = Integer.parseInt(r.get("_id").toString());
                Arrays.sort(resIds);
                updateCommand.put("$set", new BasicDBObject("wallResources", resIds));
            } else
                updateCommand.put("$push", new BasicDBObject("wallResources", r.get("_id")));
            res = collection.update(q, updateCommand, false, false, writeConcern);
        }

        /*
         * // test to see if inserted - search query BasicDBObject
         * searchQuery = new BasicDBObject(); searchQuery.put("_id",
         * Integer.parseInt(key)); // query it DBCursor cursor =
         * collection.find(searchQuery); // loop over the cursor and display
         * the retrieved result while (cursor.hasNext()) {
         * System.out.println(cursor.next()); } return 0;
         */
    } catch (Exception e) {
        System.out.println(e.toString());
        return -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return res.getError() == null ? 0 : -1;
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int acceptFriend(int invitorID, int inviteeID) {
    // delete from pending of the invitee
    // add to confirmed of both invitee and invitor
    int retVal = 0;
    if (invitorID < 0 || inviteeID < 0)
        return -1;

    com.mongodb.DB db = null;/*from  ww w. ja v a 2  s  .  c o m*/
    try {
        db = mongo.getDB(database);
        db.requestStart();
        DBCollection collection = db.getCollection("users");
        DBObject q = new BasicDBObject().append("_id", inviteeID);

        // pull out of invitees pending
        BasicDBObject updateCommand = new BasicDBObject();
        updateCommand.put("$pull", new BasicDBObject("PendFriends", invitorID));
        WriteResult res = collection.update(q, updateCommand, false, false, writeConcern);

        // add to invitees confirmed
        updateCommand = new BasicDBObject();
        updateCommand.put("$push", new BasicDBObject("ConfFriends", invitorID));
        res = collection.update(q, updateCommand, false, false, writeConcern);

        // add to invitore confirmed
        q = new BasicDBObject().append("_id", invitorID);
        updateCommand = new BasicDBObject();
        updateCommand.put("$push", new BasicDBObject("ConfFriends", inviteeID));
        res = collection.update(q, updateCommand, false, false, writeConcern);
        db.requestDone();
        return res.getN() == 1 ? 0 : -1;

    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;

}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int rejectFriend(int invitorID, int inviteeID) {
    // remove from pending of invitee
    int retVal = 0;
    if (invitorID < 0 || inviteeID < 0)
        return -1;

    com.mongodb.DB db = null;//from  w w  w .  j a  v a2s  .co m
    try {
        db = mongo.getDB(database);
        db.requestStart();
        DBCollection collection = db.getCollection("users");
        DBObject q = new BasicDBObject().append("_id", inviteeID);

        // pull out of invitees pending
        BasicDBObject updateCommand = new BasicDBObject();
        updateCommand.put("$pull", new BasicDBObject("PendFriends", invitorID));
        WriteResult res = collection.update(q, updateCommand, false, false, writeConcern);
        db.requestDone();
        return res.getN() == 1 ? 0 : -1;
    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int inviteFriend(int invitorID, int inviteeID) {
    // add to pending for the invitee
    int retVal = 0;
    if (invitorID < 0 || inviteeID < 0)
        return -1;
    com.mongodb.DB db = null;/*ww  w  .  j a va2s. c  o  m*/
    try {
        db = mongo.getDB(database);

        db.requestStart();
        DBCollection collection = db.getCollection("users");
        DBObject q = new BasicDBObject().append("_id", inviteeID);

        BasicDBObject updateCommand = new BasicDBObject();
        updateCommand.put("$push", new BasicDBObject("PendFriends", invitorID));
        WriteResult res = collection.update(q, updateCommand, false, false, writeConcern);
    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int postCommentOnResource(int commentCreatorID, int profileOwnerID, int resourceID,
        HashMap<String, ByteIterator> commentValues) {
    int retVal = 0;
    if (profileOwnerID < 0 || commentCreatorID < 0 || resourceID < 0)
        return -1;
    // create a new document
    com.mongodb.DB db = null;/*from w w w . ja v a 2 s  . c o m*/
    try {
        // get the appropriate database
        db = mongo.getDB(database);
        db.requestStart();
        if (!manipulationArray) { // consider a separate manipoulations
            // table
            DBCollection collection = db.getCollection("manipulation");
            // create the row-object-document
            // need to insert key as integer else the sorting based on id
            // for topk s wont happen properly
            HashMap<String, ByteIterator> values = new HashMap<String, ByteIterator>();
            values.put("mid", commentValues.get("mid"));
            values.put("creatorid", new ObjectByteIterator(Integer.toString(profileOwnerID).getBytes()));
            values.put("rid", new ObjectByteIterator(Integer.toString(resourceID).getBytes()));
            values.put("modifierid", new ObjectByteIterator(Integer.toString(commentCreatorID).getBytes()));
            values.put("timestamp", commentValues.get("timestamp"));
            values.put("type", commentValues.get("type"));
            values.put("content", commentValues.get("content"));

            DBObject r = new BasicDBObject();
            for (String k : values.keySet()) {
                r.put(k, values.get(k).toString());
            }

            WriteResult res = collection.insert(r, writeConcern);
            return res.getError() == null ? 0 : -1;
        } else {
            // second approach - store manipulations as elements in an array
            // for resource
            HashMap<String, String> sVals = new HashMap<String, String>();
            sVals.put("mid", commentValues.get("mid").toString());
            sVals.put("creatorid", Integer.toString(profileOwnerID));
            sVals.put("rid", Integer.toString(resourceID));
            sVals.put("modifierid", Integer.toString(commentCreatorID));
            sVals.put("timestamp", commentValues.get("timestamp").toString());
            sVals.put("type", commentValues.get("type").toString());
            sVals.put("content", commentValues.get("content").toString());
            DBCollection collection = db.getCollection("resources");
            DBObject q = new BasicDBObject().append("_id", resourceID);

            BasicDBObject updateCommand = new BasicDBObject();
            updateCommand.put("$push", new BasicDBObject("Manipulations", sVals));
            WriteResult res = collection.update(q, updateCommand, false, false, writeConcern);
            db.requestDone();
            return res.getError() == null ? 0 : -1;
        }

    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int delCommentOnResource(int resourceCreatorID, int resourceID, int manipulationID) {
    int retVal = 0;
    if (resourceCreatorID < 0 || resourceID < 0 || manipulationID < 0)
        return -1;
    com.mongodb.DB db = null;/*from   w  w w.j  a v a 2 s  .  c o m*/
    try {
        // get the appropriate database
        db = mongo.getDB(database);
        db.requestStart();
        if (!manipulationArray) { // consider a separate manipoulations
            // table
            DBCollection collection = db.getCollection("manipulation");
            DBObject q = new BasicDBObject().append("mid", Integer.toString(manipulationID)).append("rid",
                    Integer.toString(resourceID));

            collection.remove(q);

        } else {
            DBCollection collection = db.getCollection("resources");
            DBObject q = new BasicDBObject().append("_id", resourceID);
            BasicDBObject updateCommand = new BasicDBObject("Manipulations",
                    new BasicDBObject("mid", Integer.toString(manipulationID)));
            WriteResult res = collection.update(q, new BasicDBObject("$pull", updateCommand), false, false,
                    writeConcern);
            if (res.getN() != 1)
                return -1;
        }

    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int thawFriendship(int friendid1, int friendid2) {
    // delete from both their confFriends
    int retVal = 0;
    if (friendid1 < 0 || friendid2 < 0)
        return -1;

    com.mongodb.DB db = null;//from   w w w. j a va 2  s  .  com
    try {
        db = mongo.getDB(database);
        db.requestStart();
        DBCollection collection = db.getCollection("users");
        DBObject q = new BasicDBObject().append("_id", friendid1);

        // pull out of friend1
        BasicDBObject updateCommand = new BasicDBObject();
        updateCommand.put("$pull", new BasicDBObject("ConfFriends", friendid2));
        WriteResult res = collection.update(q, updateCommand, false, false, writeConcern);
        if (res.getN() != 1)
            return -1;

        q = new BasicDBObject().append("_id", friendid2);
        // pull out of friendid2
        updateCommand = new BasicDBObject();
        updateCommand.put("$pull", new BasicDBObject("ConfFriends", friendid1));
        res = collection.update(q, updateCommand, false, false, writeConcern);

        db.requestDone();
        return res.getN() == 1 ? 0 : -1;

    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public void reconstructSchema() {
    com.mongodb.DB db = null;/*from  w  ww .j av  a 2  s  .c  o m*/
    try {
        db = mongo.getDB(database);
        db.requestStart();
        // getting the number of users
        DBCollection collection = db.getCollection("users");
        int numUsers = (int) collection.getCount();
        // for every user set their conf Friends and pend Friends to null
        for (int i = 0; i < numUsers; i++) {
            DBObject r = new BasicDBObject().append("_id", i);
            DBObject queryResult = collection.findOne(r);
            BasicDBObject updateCommand = new BasicDBObject();
            updateCommand.put("$set", new BasicDBObject("ConfFriends", new ArrayList<Integer>()));
            WriteResult res = collection.update(r, updateCommand, false, false, writeConcern);
            updateCommand = new BasicDBObject();
            updateCommand.put("$set", new BasicDBObject("PendFriends", new ArrayList<Integer>()));
            res = collection.update(r, updateCommand, false, false, writeConcern);
        }
        if (manipulationArray) {
            collection = db.getCollection("resources");
            int numResources = (int) collection.getCount();
            // for every user set their conf Friends and pend Friends to null
            for (int i = 0; i < numUsers; i++) {
                DBObject r = new BasicDBObject().append("_id", i);
                DBObject queryResult = collection.findOne(r);
                BasicDBObject updateCommand = new BasicDBObject();
                updateCommand.put("$set", new BasicDBObject("Manipulations", new ArrayList<Integer>()));
                WriteResult res = collection.update(r, updateCommand, false, false, writeConcern);
            }
        } else {
            collection = db.getCollection("manipulation");
            //TODO: test this
            if (Boolean.parseBoolean(
                    props.getProperty(MONGODB_SHARDING_PROPERTY, MONGODB_SHARDING_PROPERTY_DEFAULT)) == true)
                collection.drop(); //this doesnt work with shards
            else {
                DBCursor DBCur = collection.find();
                while (DBCur.hasNext())
                    collection.remove(DBCur.next());
            }

        }

        db.requestDone();
    } catch (Exception ex) {
        db.requestDone();
        ex.printStackTrace();
    }
}

From source file:org.chililog.server.data.Controller.java

License:Apache License

/**
 * Saves the user into mongoDB/*w  w  w  .j  a  va 2  s. co  m*/
 * 
 * @param db
 *            MongoDb connection
 * @param businessObject
 *            Business object to save
 * @throws ChiliLogException
 *             if there is an error during saving
 */
public void save(DB db, BO businessObject) throws ChiliLogException {
    if (db == null) {
        throw new NullArgumentException("db");
    }
    if (businessObject == null) {
        throw new NullArgumentException("businessObject");
    }

    try {
        DBObject obj = businessObject.toDBObject();
        DBCollection coll = db.getCollection(this.getDBCollectionName());
        if (businessObject.isExistingRecord()) {
            long recordVersion = businessObject.getDocumentVersion();
            obj.put(BO.DOCUMENT_VERSION_FIELD_NAME, recordVersion + 1);

            BasicDBObject query = new BasicDBObject();
            query.put(BO.DOCUMENT_ID_FIELD_NAME, obj.get(BO.DOCUMENT_ID_FIELD_NAME));
            query.put(BO.DOCUMENT_VERSION_FIELD_NAME, recordVersion);

            coll.update(query, obj, false, false, this.getDBWriteConern());
        } else {
            obj.put(BO.DOCUMENT_VERSION_FIELD_NAME, (long) 1);
            coll.insert(obj);
        }
    } catch (MongoException ex) {
        throw new ChiliLogException(ex, Strings.MONGODB_SAVE_ERROR, ex.getMessage());
    }
}

From source file:org.grails.datastore.mapping.mongo.engine.MongoEntityPersister.java

License:Apache License

@Override
public void updateEntry(final PersistentEntity persistentEntity, final EntityAccess ea, final Object key,
        final DBObject entry) {
    mongoTemplate.execute(new DbCallback<Object>() {
        public Object doInDB(DB con) throws MongoException, DataAccessException {
            @SuppressWarnings("hiding")
            String collectionName = getCollectionName(persistentEntity, entry);
            DBCollection dbCollection = con.getCollection(collectionName);
            DBObject dbo = createDBObjectWithKey(key);

            if (isVersioned(ea)) {
                // TODO this should be done with a CAS approach if possible
                DBObject previous = dbCollection.findOne(dbo);
                checkVersion(ea, previous, persistentEntity, key);
            }//from w w w .  j av a 2 s  .c  o m

            MongoSession mongoSession = (MongoSession) session;
            dbCollection.update(dbo, entry, false, false, mongoSession.getWriteConcern());
            return null;
        }
    });
}