public Todo update(String todoId, String body) { Todo todo = new Gson().fromJson(body, Todo.class); collection.update( new BasicDBObject("_id", new ObjectId(todoId)), new BasicDBObject("$set", new BasicDBObject("done", todo.isDone()))); return this.find(todoId); }
private void handleUser(ISFSEvent event) { trace("Registered user logged in", userName); DBCollection users = AuthorizeExtension.users; BasicDBObject query = new BasicDBObject(); query.put("email", userName); DBCursor cursor = users.find(query); if (!cursor.hasNext()) { trace("user not found"); return; } document = cursor.next(); String password_digest = (String) document.get("password_digest"); if (!getApi().checkSecurePassword(session, password_digest, cryptedPass)) { trace("password wrong"); return; } document.put("session", generateSession); users.update(query, document); isRegistered = true; }
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(); DB database = client.getDB("school"); DBCollection collection = database.getCollection("students"); /* Hint/spoiler: With the new schema, this problem is a lot harder and that is sort of the point. One way is to find the lowest homework in code and then update the scores array with the low homework pruned. If you are struggling with the Node.js side of this, look at the .slice() operator, which can remove an element from an array in-place. */ DBCursor cursor = collection.find(); try { while (cursor.hasNext()) { BasicDBObject student = (BasicDBObject) cursor.next(); int studentId = student.getInt("_id"); String name = student.getString("name"); BasicDBList scores = (BasicDBList) student.get("scores"); System.out.printf("_id[%d], name[%s], scores%s %n", studentId, name, scores); DBObject scoreToRemove = null; double minScoreValue = 100.0; for (Object obj : scores) { BasicDBObject score = (BasicDBObject) obj; String type = score.getString("type"); if (!"homework".equals(type)) { continue; } double curScoreValue = score.getDouble("score"); System.out.printf("type[%s], current score value[%f] %n", type, curScoreValue); if (curScoreValue < minScoreValue) { scoreToRemove = score; minScoreValue = curScoreValue; } } System.out.printf("score to remove[%s] %n", scoreToRemove); if (scoreToRemove != null) { scores.remove(scoreToRemove); BasicDBObject query = new BasicDBObject("_id", studentId); BasicDBObject scoresUpdate = new BasicDBObject("$set", new BasicDBObject("scores", scores)); WriteResult result = collection.update(query, scoresUpdate); System.out.printf("update count[%d] %n", result.getN()); } } } finally { cursor.close(); } }
public void updateDocument(String collection, DBObject query, DBObject document) { DBCollection dbCollection = getCollection(collection); dbCollection.update(query, document); Jedis jedis = JedisManager.getJedis(); if (jedis.hexists(collection, query.toString())) { jedis.hset(collection, query.toString(), findOneNoCache(collection, query).toString()); jedis.zadd("expire", System.currentTimeMillis() + 300000, collection + "_" + query); } JedisManager.returnJedis(jedis); }
@Test public void testUpsert() { DBCollection c = _db.getCollection("upsert1"); c.drop(); c.update( new BasicDBObject("page", "/"), new BasicDBObject("$inc", new BasicDBObject("count", 1)), true, false); c.update( new BasicDBObject("page", "/"), new BasicDBObject("$inc", new BasicDBObject("count", 1)), true, false); assertEquals(1, c.getCount()); assertEquals(2, c.findOne().get("count")); }
public void performBatch(List<BatchUnit> rows) { if (logger.isTraceEnabled()) { logger.trace("MongoClientWrapper.performBatch(" + rows + ")"); logger.trace("Batch size to be performed is " + rows.size()); } // List<Future<? extends Number>> pending = new ArrayList<Future<? extends Number>>(); for (BatchUnit row : rows) { SpaceDocument spaceDoc = row.getSpaceDocument(); SpaceTypeDescriptor typeDescriptor = types.get(row.getTypeName()).getTypeDescriptor(); SpaceDocumentMapper<DBObject> mapper = getMapper(typeDescriptor); DBObject obj = mapper.toDBObject(spaceDoc); DBCollection col = getCollection(row.getTypeName()); switch (row.getDataSyncOperationType()) { case WRITE: case UPDATE: col.save(obj); break; case PARTIAL_UPDATE: DBObject query = BasicDBObjectBuilder.start() .add(Constants.ID_PROPERTY, obj.get(Constants.ID_PROPERTY)) .get(); DBObject update = normalize(obj); col.update(query, update); break; // case REMOVE_BY_UID: // Not supported by this implementation case REMOVE: col.remove(obj); break; default: throw new IllegalStateException( "Unsupported data sync operation type: " + row.getDataSyncOperationType()); } } /*long totalCount = waitFor(pending); if (logger.isTraceEnabled()) { logger.trace("total accepted replies is: " + totalCount); }*/ }
@Override public void update(TestData testData) { try { DB db = MongoDBProvider.getInstance().getDB(); DBCollection coll = db.getCollection("testdata"); BasicDBObject query = new BasicDBObject(); query.put("source", testData.getClassName()); BasicDBObject object = new BasicDBObject(); object.put("source", testData.getClassName()); object.put("fails", testData.getFails()); coll.update(query, object, true, false); } catch (MongoException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } }
public static void main(String[] args) { try { // connect to mongoDB, ip and port number Mongo mongo = new Mongo("127.0.0.1", 27017); // get database from MongoDB, // if database doesn't exists, mongoDB will create it automatically DB db = mongo.getDB("yourdb"); // Getting A List Of Collections Set<String> collections = db.getCollectionNames(); for (String s : collections) { System.out.println(s); } // Get collection from MongoDB, database named "yourDB" // if collection doesn't exists, mongoDB will create it automatically DBCollection collection = db.getCollection("yourCollection"); // create a document to store key and value DBObject document = new BasicDBObject(); document.put("id", 1001); document.put("msg", "hello world mongoDB in Java"); // save it into collection named "yourCollection" collection.insert(document); // search query DBObject searchQuery = new BasicDBObject(); searchQuery.put("id", 1001); // query it DBCursor cursor = collection.find(searchQuery); // loop over the cursor and display the retrieved result while (cursor.hasNext()) { System.out.println("Our collection after putting document here: " + cursor.next()); } // Counting Documents in Collection System.out.println("Elements in collection " + collection.getCount()); // update document (just replase exist - it is normal practise) DBObject updatedDocument = new BasicDBObject(); updatedDocument.put("id", 1001); updatedDocument.put("msg", "hello world mongoDB in Java updated"); collection.update(new BasicDBObject().append("id", 1001), updatedDocument); // query it DBCursor cursorAfterUpdate = collection.find(searchQuery); // loop over the cursor and display the retrieved result while (cursorAfterUpdate.hasNext()) { System.out.println("Our collection after update: " + cursorAfterUpdate.next()); } // Counting Documents in Collection System.out.println("Elements in collection " + collection.getCount()); // Map to object Message message = new Message(); message.setId((Integer) document.get("id")); message.setMessage((String) document.get("msg")); System.out.println("Id putted in object: " + message.getId()); System.out.println("Message putted in object: " + message.getMessage()); // Remove document from collection DBObject doc = collection.findOne(); // get first document collection.remove(doc); // query it DBCursor cursorAfterDelete = collection.find(searchQuery); // loop over the cursor and display the retrieved result while (cursorAfterDelete.hasNext()) { System.out.println("Our collection after delete: " + cursorAfterDelete.next()); } // Counting Documents in Collection System.out.println("Elements in collection " + collection.getCount()); // Close connection to db mongo.close(); System.out.println("Done"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } }