@Test public void testRenameAndDrop() throws MongoException { String namea = "testRenameA"; String nameb = "testRenameB"; DBCollection a = getDatabase().getCollection(namea); DBCollection b = getDatabase().getCollection(nameb); a.drop(); b.drop(); assertEquals(0, a.find().count()); assertEquals(0, b.find().count()); a.save(new BasicDBObject("x", 1)); b.save(new BasicDBObject("x", 1)); assertEquals(1, a.find().count()); assertEquals(1, b.find().count()); DBCollection b2 = a.rename(nameb, true); assertEquals(0, a.find().count()); assertEquals(1, b.find().count()); assertEquals(1, b2.find().count()); assertEquals(b.getName(), b2.getName()); }
@Test public void testBatchWithActiveCursor() { DBCollection c = _db.getCollection("testBatchWithActiveCursor"); c.drop(); for (int i = 0; i < 100; i++) c.save(new BasicDBObject("x", i)); try { DBCursor cursor = c.find().batchSize(2); // setting to 1, actually sets to 2 (why, oh why?) cursor.next(); // creates real cursor on server. cursor.next(); assertEquals(0, cursor.numGetMores()); cursor.next(); assertEquals(1, cursor.numGetMores()); cursor.next(); cursor.next(); assertEquals(2, cursor.numGetMores()); cursor.next(); cursor.next(); assertEquals(3, cursor.numGetMores()); cursor.batchSize(20); cursor.next(); cursor.next(); cursor.next(); assertEquals(4, cursor.numGetMores()); } catch (IllegalStateException e) { assertNotNull(e); // there must be a better way to detect this. } }
public void introduceType(SpaceTypeDescriptor typeDescriptor) { DBCollection m = getConnection().getCollection(METADATA_COLLECTION_NAME); BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().add(Constants.ID_PROPERTY, typeDescriptor.getTypeName()); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); IOUtils.writeObject( out, SpaceTypeDescriptorVersionedSerializationUtils.toSerializableForm(typeDescriptor)); builder.add(TYPE_DESCRIPTOR_FIELD_NAME, bos.toByteArray()); WriteResult wr = m.save(builder.get()); if (logger.isTraceEnabled()) logger.trace(wr); indexBuilder.ensureIndexes(typeDescriptor); } catch (IOException e) { logger.error(e); throw new SpaceMongoException( "error occurs while serialize and save type descriptor: " + typeDescriptor, e); } }
@Test public void testExplain() { DBCollection c = _db.getCollection("explain1"); c.drop(); for (int i = 0; i < 100; i++) c.save(new BasicDBObject("x", i)); DBObject q = BasicDBObjectBuilder.start().push("x").add("$gt", 50).get(); assertEquals(49, c.find(q).count()); assertEquals(49, c.find(q).itcount()); assertEquals(49, c.find(q).toArray().size()); assertEquals(49, c.find(q).itcount()); assertEquals(20, c.find(q).limit(20).itcount()); assertEquals(20, c.find(q).limit(-20).itcount()); c.ensureIndex(new BasicDBObject("x", 1)); assertEquals(49, c.find(q).count()); assertEquals(49, c.find(q).toArray().size()); assertEquals(49, c.find(q).itcount()); assertEquals(20, c.find(q).limit(20).itcount()); assertEquals(20, c.find(q).limit(-20).itcount()); assertEquals(49, c.find(q).explain().get("n")); assertEquals(20, c.find(q).limit(20).explain().get("n")); assertEquals(20, c.find(q).limit(-20).explain().get("n")); }
/** * Adds privilege documents to the {@code system.users} collection in a database, which creates * database credentials in MongoDB. * * @param username * @param passwd * @param readOnly if true, user will only be able to read * @throws MongoException */ public WriteResult addUser(String username, char[] passwd, boolean readOnly) { DBCollection c = getCollection("system.users"); DBObject o = c.findOne(new BasicDBObject("user", username)); if (o == null) o = new BasicDBObject("user", username); o.put("pwd", _hash(username, passwd)); o.put("readOnly", readOnly); return c.save(o); }
@Test // (enabled = false) public void testTailableAwait() throws ExecutionException, TimeoutException, InterruptedException { DBCollection c = _db.getCollection("tail1"); c.drop(); _db.createCollection("tail1", new BasicDBObject("capped", true).append("size", 10000)); for (int i = 0; i < 10; i++) { c.save(new BasicDBObject("x", i), WriteConcern.SAFE); } final DBCursor cur = c.find() .sort(new BasicDBObject("$natural", 1)) .addOption(Bytes.QUERYOPTION_TAILABLE | Bytes.QUERYOPTION_AWAITDATA); Callable<Object> callable = new Callable<Object>() { @Override public Object call() throws Exception { try { // the following call will block on the last hasNext int i = 0; while (cur.hasNext()) { DBObject obj = cur.next(); i++; if (i > 10) return obj.get("x"); } return null; } catch (Throwable e) { return e; } } }; ExecutorService es = Executors.newSingleThreadExecutor(); Future<Object> future = es.submit(callable); Thread.sleep(5000); assertTrue(!future.isDone()); // this doc should unblock thread c.save(new BasicDBObject("x", 10), WriteConcern.SAFE); Object retVal = future.get(5, TimeUnit.SECONDS); assertEquals(10, retVal); }
@Test public void testGetCollectionNames() throws MongoException { String name = "testGetCollectionNames"; DBCollection c = getDatabase().getCollection(name); c.drop(); assertFalse(getDatabase().getCollectionNames().contains(name)); c.save(new BasicDBObject("x", 1)); assertTrue(getDatabase().getCollectionNames().contains(name)); }
public static void insert() throws UnknownHostException { Mongo mongoClient = new Mongo("localhost", 27017); DB db = mongoClient.getDB("developers"); DBCollection coll = db.getCollection("developers"); Developer developer = new Developer("Oscar", "Wilde", 50); coll.save(developer); }
@Test public void testBatchWithLimit() { DBCollection c = _db.getCollection("batchWithLimit1"); c.drop(); for (int i = 0; i < 100; i++) c.save(new BasicDBObject("x", i)); assertEquals(50, c.find().limit(50).itcount()); assertEquals(50, c.find().batchSize(5).limit(50).itcount()); }
@Test(groups = {"basic"}) public void testSnapshot() { DBCollection c = _db.getCollection("snapshot1"); c.drop(); for (int i = 0; i < 100; i++) c.save(new BasicDBObject("x", i)); assertEquals(100, c.find().count()); assertEquals(100, c.find().toArray().size()); assertEquals(100, c.find().snapshot().count()); assertEquals(100, c.find().snapshot().toArray().size()); assertEquals(100, c.find().snapshot().limit(50).count()); assertEquals(50, c.find().snapshot().limit(50).toArray().size()); }
public void updateValidity(String user, String token) { DBCollection coll = db().getCollection(M_TOKENS); BasicDBObject query = new BasicDBObject(); query.put("user", user); query.put("token", token); DBCursor cursor = coll.find(query); while (cursor.hasNext()) { DBObject doc = cursor.next(); doc.put("validity", System.currentTimeMillis()); coll.save(doc, WriteConcern.SAFE); } }
@Test public void testLargeBatch() { DBCollection c = _db.getCollection("largeBatch1"); c.drop(); int total = 50000; int batch = 10000; for (int i = 0; i < total; i++) c.save(new BasicDBObject("x", i)); DBCursor cursor = c.find().batchSize(batch); assertEquals(total, cursor.itcount()); assertEquals(total / batch + 1, cursor.getSizes().size()); }
@Test // (enabled = false) public void testTailable() { DBCollection c = _db.getCollection("tail1"); c.drop(); _db.createCollection("tail1", new BasicDBObject("capped", true).append("size", 10000)); for (int i = 0; i < 10; i++) { c.save(new BasicDBObject("x", i)); } DBCursor cur = c.find().sort(new BasicDBObject("$natural", 1)).addOption(Bytes.QUERYOPTION_TAILABLE); while (cur.hasNext()) { cur.next(); // do nothing... } assert (!cur.hasNext()); c.save(new BasicDBObject("x", 12)); assert (cur.hasNext()); assertNotNull(cur.next()); assert (!cur.hasNext()); }
@Test public void saveThisTweet() throws Exception { Tweet tweet = new Tweet("100000", "XebiaFR", new Date(), "Discovering #mongodb"); DBObject dbObject = new BasicDBObject(); dbObject.put("from_user_id", tweet.getUserId()); dbObject.put("from_user_name", tweet.getUserName()); dbObject.put("created_at", tweet.getCreateAt()); dbObject.put("text", tweet.getText()); collection.save(dbObject, WriteConcern.SAFE); assertThat(collection.count()).isGreaterThan(0); }
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); }*/ }
@Test public void testBig() { DBCollection c = _db.getCollection("big1"); c.drop(); String bigString; { StringBuilder buf = new StringBuilder(16000); for (int i = 0; i < 16000; i++) buf.append("x"); bigString = buf.toString(); } int numToInsert = (15 * 1024 * 1024) / bigString.length(); for (int i = 0; i < numToInsert; i++) c.save(BasicDBObjectBuilder.start().add("x", i).add("s", bigString).get()); assert (800 < numToInsert); assertEquals(numToInsert, c.find().count()); assertEquals(numToInsert, c.find().toArray().size()); assertEquals(numToInsert, c.find().limit(800).count()); assertEquals(800, c.find().limit(800).toArray().size()); // negative limit works like negative batchsize, for legacy reason int x = c.find().limit(-800).toArray().size(); assertLess(x, 800); DBCursor a = c.find(); assertEquals(numToInsert, a.itcount()); DBCursor b = c.find().batchSize(10); assertEquals(numToInsert, b.itcount()); assertEquals(10, b.getSizes().get(0).intValue()); assertLess(a.numGetMores(), b.numGetMores()); assertEquals(numToInsert, c.find().batchSize(2).itcount()); assertEquals(numToInsert, c.find().batchSize(1).itcount()); assertEquals(numToInsert, _count(c.find(null, null).skip(0).batchSize(5))); assertEquals(5, _count(c.find(null, null).skip(0).batchSize(-5))); }
@Test public void testHasFinalizer() throws UnknownHostException { DBCollection c = _db.getCollection("HasFinalizerTest"); c.drop(); for (int i = 0; i < 1000; i++) c.save(new BasicDBObject("_id", i), WriteConcern.SAFE); // finalizer is on by default so after calling hasNext should report that it has one DBCursor cursor = c.find(); assertFalse(cursor.hasFinalizer()); cursor.hasNext(); assertTrue(cursor.hasFinalizer()); cursor.close(); // no finalizer if there is no cursor, as there should not be for a query with only one result cursor = c.find(new BasicDBObject("_id", 1)); cursor.hasNext(); assertFalse(cursor.hasFinalizer()); cursor.close(); // no finalizer if there is no cursor, as there should not be for a query with negative batch // size cursor = c.find(); cursor.batchSize(-1); cursor.hasNext(); assertFalse(cursor.hasFinalizer()); cursor.close(); // finally, no finalizer if disabled in mongo options MongoOptions mongoOptions = new MongoOptions(); mongoOptions.cursorFinalizerEnabled = false; Mongo m = new Mongo("127.0.0.1", mongoOptions); try { c = m.getDB(cleanupDB).getCollection("HasFinalizerTest"); cursor = c.find(); cursor.hasNext(); assertFalse(cursor.hasFinalizer()); cursor.close(); } finally { m.close(); } }
@Test public void testLimitAndBatchSize() { DBCollection c = _db.getCollection("LimitAndBatchSize"); c.drop(); for (int i = 0; i < 1000; i++) c.save(new BasicDBObject("x", i)); DBObject q = BasicDBObjectBuilder.start().push("x").add("$lt", 200).get(); DBCursor cur = c.find(q); assertEquals(0, cur.getCursorId()); assertEquals(200, cur.itcount()); cur = c.find(q).limit(50); assertEquals(0, cur.getCursorId()); assertEquals(50, cur.itcount()); cur = c.find(q).batchSize(50); assertEquals(0, cur.getCursorId()); assertEquals(200, cur.itcount()); cur = c.find(q).batchSize(100).limit(50); assertEquals(0, cur.getCursorId()); assertEquals(50, cur.itcount()); cur = c.find(q).batchSize(-40); assertEquals(0, cur.getCursorId()); assertEquals(40, cur.itcount()); cur = c.find(q).limit(-100); assertEquals(0, cur.getCursorId()); assertEquals(100, cur.itcount()); cur = c.find(q).batchSize(-40).limit(20); assertEquals(0, cur.getCursorId()); assertEquals(20, cur.itcount()); cur = c.find(q).batchSize(-20).limit(100); assertEquals(0, cur.getCursorId()); assertEquals(20, cur.itcount()); }
@Test(groups = "dev") public void collectionTest() { DB db = mongo.getDB(DBNAME); DBCollection myCollection = db.getCollection("myCollection"); myCollection.save( new BasicDBObject( MapUtils.putAll(new HashMap(), new Object[] {"name", "leon", "age", 33}))); myCollection.findOne(); Set<String> names = db.getCollectionNames(); assertNotNull(names); boolean hit = false; for (String name : names) { if ("myCollection".equals(name)) { hit = true; break; } } assertTrue(hit); }
@Test public void testSort() { DBCollection c = _db.getCollection("SortTest"); c.drop(); for (int i = 0; i < 1000; i++) c.save(new BasicDBObject("x", i).append("y", 1000 - i)); // x ascending DBCursor cur = c.find().sort(new BasicDBObject("x", 1)); int curmax = -100; while (cur.hasNext()) { int val = (Integer) cur.next().get("x"); assertTrue(val > curmax); curmax = val; } // x desc cur = c.find().sort(new BasicDBObject("x", -1)); curmax = 9999; while (cur.hasNext()) { int val = (Integer) cur.next().get("x"); assertTrue(val < curmax); curmax = val; } // query and sort cur = c.find(QueryBuilder.start("x").greaterThanEquals(500).get()) .sort(new BasicDBObject("y", 1)); assertEquals(500, cur.count()); curmax = -100; while (cur.hasNext()) { int val = (Integer) cur.next().get("y"); assertTrue(val > curmax); curmax = val; } }
public WriteResult save(Object pojo) { Object id = preparePojo(pojo); return collection.save(convertToDBObject(pojo, id), writeConcern); }