private List<String> selectViewCodes(String schema) throws UnknownHostException { // Initiate variables List<String> l = new ArrayList<String>(); MongoDBConnectionManager mgr = MongoDBConnectionManager.getInstance(); Mongo mongo = mgr.getMongo(); DB db = mongo.getDB(schema); DBCollection collection = db.getCollection("views"); // Compose NoSQL query BasicDBObject groupFiels = new BasicDBObject("_id", "$view_id"); BasicDBObject group = new BasicDBObject("$group", groupFiels); BasicDBObject sortFiels = new BasicDBObject("_id", 1); BasicDBObject sort = new BasicDBObject("$sort", sortFiels); // Create the output AggregationOutput output = collection.aggregate(group, sort); Iterable<DBObject> results = output.results(); for (DBObject result : results) { try { l.add(result.get("_id").toString()); } catch (NullPointerException e) { System.out.println("Skipping NULL"); } } // Return the result return l; }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // response.getWriter().append("Served at: ").append(request.getContextPath()); MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds019028.mlab.com:19028/asedb"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); DBCollection users = db.getCollection("UserRecords"); BasicDBObject query = new BasicDBObject(); String firstname = request.getParameter("FirstName"); String lastname = request.getParameter("LastName"); String email = request.getParameter("email"); String password = request.getParameter("EnterPassword"); String confpasswd = request.getParameter("ConfirmPassword"); query.put("First Name", firstname); query.put("Last Name", lastname); query.put("Email", email); System.out.println(email); if (password == confpasswd) { query.put("Password", password); } else { } DBCursor docs = users.find(query); response.getWriter().write(docs.toArray().toString()); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); System.out.println("Insert doget"); }
@Override public String IngresarJson(String nombreDB, String json, int clienteId) throws UnknownHostException { // TODO Auto-generated method stub MongoClient mongoClient = new MongoClient("localhost", 27017); DB base = mongoClient.getDB(nombreDB); // Ya existe if (ExisteCliente(nombreDB, clienteId)) { // System.out.println("********************\n"); // System.out.println("Ya existe cliente, error no se igresa el Json"); // System.out.println("********************\n"); return "Ya existe cliente, error no se igresa el Json"; } // no existe el cliente DBCollection collection = base.getCollection("Json"); BasicDBObject document = new BasicDBObject(); document.put("id", clienteId); DBObject object = (DBObject) JSON.parse(json); document.put("json", object); // document.put("json",json); collection.insert(document); return "Ok"; }
public static void main(String[] args) throws IOException { String term = JOptionPane.showInputDialog( "Welcome to our knock-off search engine! \nPlease enter a term to search:"); while (term == null || term.isEmpty()) { term = JOptionPane.showInputDialog( "You didn't input anything! \nPlease enter a term to search: "); } MongoClient mongoClient = new MongoClient("localhost", 27017); System.out.println("Establishing connection..."); // Get the connection. DB db = mongoClient.getDB("crawler"); DBCollection table = db.getCollection("urlpages"); System.out.println("Connected to MongoDB!"); db.getCollection("pagerank").drop(); Ranking ranker = new Ranking(db); ranker.link_analysis(); ranker.TFIDF(term); run(term, db); JOptionPane.showMessageDialog( null, "Search is completed! \nPlease refer to 'C:\\data\\search_results.json' for the result."); }
public static void main(String[] args) throws Exception { // connect to the local database server MongoClient mongoClient = new MongoClient(); // Authenticate - optional // boolean auth = db.authenticate("foo", "bar"); // get db names for (String s : mongoClient.getDatabaseNames()) { System.out.println(s); } // get a db DB db = mongoClient.getDB("com_mongodb_MongoAdmin"); // do an insert so that the db will really be created. Calling getDB() doesn't really take any // action with the server db.getCollection("testcollection").insert(new BasicDBObject("i", 1)); for (String s : mongoClient.getDatabaseNames()) { System.out.println(s); } // drop a database mongoClient.dropDatabase("com_mongodb_MongoAdmin"); for (String s : mongoClient.getDatabaseNames()) { System.out.println(s); } }
@Override public void run() { MongoProfile profile = options.getProfile(); MongoClient mongo = null; DBCursor cursor = null; try { mongo = new MongoClient(profile.getAddress(), profile.getCredentials()); DB db = mongo.getDB(options.getDatabase()); DBCollection col = db.getCollection(options.getCollection()); cursor = col.find(); while (cursor.hasNext()) { DBObject doc = cursor.next(); Map<String, Object> m = convert(doc); pushPipe(new Row(m)); } } catch (Throwable t) { slog.error("araqne logdb mongo: cannot run mongo.find", t); } finally { if (cursor != null) cursor.close(); if (mongo != null) mongo.close(); } }
@Test public void testStore() { HasExpiryField hasExpiryField = new HasExpiryField(); hasExpiryField.setOfferIs("Good"); Calendar c = Calendar.getInstance(); hasExpiryField.setOfferExpiresAt(c.getTime()); ds.getMapper().addMappedClass(HasExpiryField.class); ds.ensureIndexes(); ds.save(hasExpiryField); DB db = ds.getDB(); DBCollection dbCollection = db.getCollection("HasExpiryField"); List<DBObject> indexes = dbCollection.getIndexInfo(); Assert.assertNotNull(indexes); Assert.assertEquals(2, indexes.size()); DBObject index = null; for (DBObject candidateIndex : indexes) { if (candidateIndex.containsField("expireAfterSeconds")) { index = candidateIndex; } } Assert.assertNotNull(index); Assert.assertTrue(index.containsField("expireAfterSeconds")); Assert.assertEquals(60, index.get("expireAfterSeconds")); }
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(); DB courseDB = client.getDB("course"); DBCollection list = courseDB.getCollection("DotNotationTest"); list.drop(); Random random = new Random(); for (int i = 0; i < 10; i++) { list.insert( new BasicDBObject("_id", i) .append( "start", new BasicDBObject("x", random.nextInt(2)).append("y", random.nextInt(90) + 10)) .append( "end", new BasicDBObject("x", random.nextInt(2)).append("y", random.nextInt(90) + 10))); } DBCursor cursor = list.find().sort(new BasicDBObject("start.x", 1).append("start.y", -1)).skip(2).limit(10); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
/* Returns List of Wikipedia page-ids of pages the string 'anchor' points to in Wikipedia */ public List<Long> getPages(String anchor) { db.requestStart(); List<Long> PageCollection = new ArrayList<Long>(); BasicDBObject query = new BasicDBObject(); query.put("anchor", anchor); BasicDBObject fields = new BasicDBObject("pages", true).append("_id", false); DBObject obj = table.findOne(query, fields); // System.out.println("num of results = "+curs.count()); if (obj != null) { JSONParser jp = new JSONParser(); JSONArray jarr = null; try { jarr = (JSONArray) jp.parse(obj.get("pages").toString()); } catch (ParseException e) { jarr = new JSONArray(); } // System.out.println("Link Freq = "+o.get("anchPageFreq").toString()); for (int i = 0; i < jarr.size(); i++) { JSONObject objects = (JSONObject) jarr.get(i); PageCollection.add((long) (objects.get("page_id"))); } } db.requestDone(); return PageCollection; } // End getPages()
public void test() { MongoConn conn = new MongoConn(); conn.init(); DB db = conn.getDB(); DBCollection coll = db.getCollection("testKHT"); BasicDBObject ob = new BasicDBObject(); ob.append("_id", 1); ob.append("id", 12); coll.save(ob); // ---- // DBRef addressRef = new DBRef(db, "foo.bar", "202.102.40.43"); // DBObject address = addressRef.fetch(); // // DBObject person = BasicDBObjectBuilder.start() // .add("name", "Fred") // .add("address", addressRef) // .get(); // // coll.save(person); // // DBObject fred = coll.findOne(); // DBRef addressObj = (DBRef)fred.get("address"); // addressObj.fetch(); }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // response.getWriter().append("Served at: ").append(request.getContextPath()); // JSONObject object = new JSONObject(); // object.put("message", "Hello World"); // response.getWriter().write(object.toString()); response.getWriter().write("Read Users<br /><br />"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds031611.mongolab.com:31611/testbeerdb"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); DBCollection songs = db.getCollection("users"); DBCursor docs = songs.find(); response.getWriter().write(docs.toArray().toString()); doPost(request, response); }
/** * if hourlyjob has completed,item will insert to repository db.and partial file will delete, * dailydb will delete. * * @throws UnknownHostException */ @Test public void t2() throws UnknownHostException { MongoClient mongoClient = new MongoClient(AppConstants.MONGODB_HOST, AppConstants.MONGODB_PORT); DB dailyDb = mongoClient.getDB(dailyDbName); DBCollection hourlyCol = dailyDb.getCollection(AppConstants.MongoNames.HOURLY_JOB_COL_NAME); // must drop,or complete status detect will wrong. hourlyCol.drop(); for (int idx = 24; idx > 12; idx--) { DBObject dbo = new BasicDBObject() .append(AppConstants.MongoNames.HOURLY_JOB_NUMBER_KEY, idx + "") .append(AppConstants.MongoNames.HOURLY_JOB_STATUS_KEY, "end"); hourlyCol.insert(dbo); } new DailyCopyWorkVerticle.DailyCopyProcessor( mongoClient, dailyDbName, repositoryDbName, dailyPartialDir, new JsonObject().putNumber("dailydbreadgap", 1000)) .process(); mongoClient = new MongoClient(AppConstants.MONGODB_HOST, AppConstants.MONGODB_PORT); DB db = mongoClient.getDB(repositoryDbName); DBCollection col = db.getCollection(AppConstants.MongoNames.PAGE_VISIT_COL_NAME); Assert.assertEquals(10005, col.count()); Assert.assertFalse(Files.exists(Paths.get(dailyPartialDir, dailyDbName))); }
@Override public boolean save(String collectionName, DBObject queryData, DBObject saveData) { DB db = mongoClient.getDB(mongoDB); DBCollection coll = db.getCollection(collectionName); coll.update(queryData, saveData, true, false); return false; }
public static void main(String[] args) throws UnknownHostException { System.out.println("Start Testing"); MongoClient client = new MongoClient(new ServerAddress("192.168.0.14", 27017)); DB db = client.getDB("course"); DBCollection collection = db.getCollection("findTestFromJava"); collection.drop(); for (int i = 0; i < 10; i++) { collection.insert(new BasicDBObject("x", new Random().nextInt(100))); } System.out.println("Find one:"); DBObject one = collection.findOne(); System.out.println("one = " + one); System.out.println("\nFind all:"); DBCursor cursor = collection.find(); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println("cursor = " + cur); } } finally { cursor.close(); } System.out.println("\nFind Count:"); long count = collection.count(); System.out.println("count = " + count); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("in side servlet"); PrintWriter out = response.getWriter(); try { long time = System.currentTimeMillis() - 60000; DB db = CommonDB.getBankConnection(); DB db1 = CommonDB.getConnection(); DBCollection coll = db.getCollection("Regular"); DBCollection coll1 = db1.getCollection("CISResponse"); BasicDBObject objs = new BasicDBObject("response_time", new BasicDBObject("$gt", time)); BasicDBObject objs1 = new BasicDBObject("exectime", new BasicDBObject("$gt", time)); int webUserCount = coll1.distinct("IP_Address", objs1).size(); /* * List cityList = coll.distinct("city", objs); * cityList.remove("GPS not available !!!"); */ int appUserCount = coll.distinct("UUID", objs).size(); System.out.println("count is : " + webUserCount + appUserCount); out.print("{\"WebUserCount\":" + webUserCount + ",\"AppUserCount\":" + appUserCount + "}"); } catch (Exception ex) { ex.printStackTrace(); } }
/* Returns map of Wikipedia page-ids to number of inlinks to those pages. Page ids are pages the string 'anchor' points to in Wikipedia */ public Map<Long, Integer> getPagesMap(String anchor) { db.requestStart(); Map<Long, Integer> PageCollection = new HashMap<Long, Integer>(); BasicDBObject query = new BasicDBObject(); query.put("anchor", anchor); BasicDBObject fields = new BasicDBObject("page_id", true) .append("pages", true) .append("page_freq", true) .append("anchor_freq", true) .append("_id", false); DBObject ans = table.findOne(query, fields); // System.out.println("num of results = "+curs.count()); db.requestDone(); if (ans != null) { JSONParser jp = new JSONParser(); JSONArray jo = null; try { // System.out.println(ans.get("pages")); jo = (JSONArray) jp.parse(ans.get("pages").toString()); } catch (ParseException e) { e.printStackTrace(); } // System.out.println("Link Freq = "+o.get("anchPageFreq").toString()); for (int i = 0; i < jo.size(); i++) { JSONObject object = (JSONObject) jo.get(i); Long pId = (long) (object.get("page_id")); Long pValue0 = (long) object.get("page_freq"); int pValue = pValue0.intValue(); if (PageCollection.containsKey(pId)) { pValue = PageCollection.get(pId) + pValue; } PageCollection.put(pId, pValue); } } return PageCollection; } // End getPagesMap()
public static void main(String[] args) throws UnknownHostException { Mongo client = new Mongo(); DB db = client.getDB("course"); DBCollection lines = db.getCollection("sortSkipLimitSample"); lines.drop(); Random rand = new Random(); // insert 10 lines with random start and end points for (int i = 0; i < 10; i++) { lines.insert( new BasicDBObject("_id", i) .append( "start", new BasicDBObject("x", rand.nextInt(2)).append("y", rand.nextInt(90) + 10)) .append( "end", new BasicDBObject("x", rand.nextInt(2)).append("y", rand.nextInt(90) + 10))); } DBCursor cursor = lines.find().sort(new BasicDBObject("start.x", 1).append("start.y", -1)).skip(2).limit(10); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
/** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds047752.mlab.com:47752/ase_lab7"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); DBCollection users = db.getCollection("users"); BasicDBObject query = new BasicDBObject().append("username", "Ram"); query.put("name", "Ram"); // request.getParameter("name")); query.put("password", "password"); // request.getParameter("password")); BasicDBObject newDocument = new BasicDBObject(); newDocument.put("name", "SreeRam"); users.update(query, newDocument); DBCursor docs = users.find(query); response.getWriter().write(docs.toArray().toString()); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); }
@Test public void testCreateCollection() { Fongo fongo = newFongo(); DB db = fongo.getDB("db"); db.createCollection("coll", null); assertEquals(Collections.singleton("coll"), db.getCollectionNames()); }
public void ensureCaps() { for (MappedClass mc : mapr.getMappedClasses()) if (mc.getEntityAnnotation() != null && mc.getEntityAnnotation().cap().value() > 0) { CappedAt cap = mc.getEntityAnnotation().cap(); String collName = mapr.getCollectionName(mc.getClazz()); BasicDBObjectBuilder dbCapOpts = BasicDBObjectBuilder.start("capped", true); if (cap.value() > 0) dbCapOpts.add("size", cap.value()); if (cap.count() > 0) dbCapOpts.add("max", cap.count()); DB db = getDB(); if (db.getCollectionNames().contains(collName)) { DBObject dbResult = db.command(BasicDBObjectBuilder.start("collstats", collName).get()); if (dbResult.containsField("capped")) { // TODO: check the cap options. log.warning("DBCollection already exists is cap'd already; doing nothing. " + dbResult); } else { log.warning( "DBCollection already exists with same name(" + collName + ") and is not cap'd; not creating cap'd version!"); } } else { getDB().createCollection(collName, dbCapOpts.get()); log.debug("Created cap'd DBCollection (" + collName + ") with opts " + dbCapOpts); } } }
/* * mongo.local.hostname=localhost * mongo.local.port=27017 * mongo.remote.hostname= * mongo.remote.port=25189 * mongo.remote.username= * mongo.remote.password= */ private static DB getDb() { String userName = play.Configuration.root().getString("mongo.remote.username"); String password = play.Configuration.root().getString("mongo.remote.password"); boolean local = true; String localHostName = play.Configuration.root().getString("mongo.local.hostname"); Integer localPort = play.Configuration.root().getInt("mongo.local.port"); String remoteHostName = play.Configuration.root().getString("mongo.remote.hostname"); Integer remotePort = play.Configuration.root().getInt("mongo.remote.port"); Mongo m; DB db = null; if (local) { String hostname = localHostName; int port = localPort; try { m = new Mongo(hostname, port); db = m.getDB("db"); } catch (Exception e) { Logger.error("Exception while intiating Local MongoDB", e); } } else { String hostname = remoteHostName; int port = remotePort; try { m = new Mongo(hostname, port); db = m.getDB("db"); boolean auth = db.authenticate(userName, password.toCharArray()); } catch (Exception e) { Logger.error("Exception while intiating Local MongoDB", e); } } return db; }
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(); DB db = client.getDB("course"); DBCollection collection = db.getCollection("findCriteriaTest"); collection.drop(); for (int i = 0; i < 10; i++) { collection.insert( new BasicDBObject("x", new Random().nextInt(2)).append("y", new Random().nextInt(100))); } QueryBuilder builder = QueryBuilder.start("x").is(0).and("y").greaterThan(10).lessThan(90); // DBObject query = new BasicDBObject("x", 0).append("y", new BasicDBObject("$gt", // 10).append("$lt", 90)); System.out.println("\nCount:"); long count = collection.count(builder.get()); System.out.println(count); System.out.println("\nFind all:"); DBCursor cursor = collection.find(builder.get()); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
private void getTweetWithRTCountGreaterThan(int gt) { Mongo mongo = null; try { mongo = new Mongo(MONGO_DB_HOST, MONGO_DB_PORT); DB db = mongo.getDB(MONGO_DB_NAME); DBCollection collection = db.getCollection(MONGO_DB_COLLECTION); DBCursor cursor = collection.find(new BasicDBObject("rTCount", new BasicDBObject("$gt", gt))); DBObject dbObject; System.out.println("\n\n========================================"); System.out.println("Displaying Tweet with RTCount > " + gt); while (cursor.hasNext()) { dbObject = cursor.next(); System.out.println( "user " + dbObject.get("user") + "tweet " + dbObject.get("tweet") + " RTCount " + dbObject.get("rTCount")); } System.out.println("========================================\n\n"); } catch (UnknownHostException e) { e.printStackTrace(); } finally { if (mongo != null) mongo.close(); } }
public <T> T execute(Statement statement) throws BasicException { CompileResult result = this.compiler.compile(statement); for (AbstractRow row : result) { final DBObject bson = row.toBSON(statement.getArgs()); final DB db = this.mongoClient.getDB(row.hasDatabase() ? row.getDatabase() : this.database); final DBCollection table = db.getCollection(row.getTable()); final AbstractRow.Mode mode = row.getMode(); switch (mode) { case insert: table.insert(bson); break; case select: break; case update: break; case delete: table.remove(bson); break; default: throw new RuntimeException("cannot recognize mode: " + mode); } } return null; }
@Before public void init() throws IOException { action = new MethodMsgAction(); MapPubSub pubSub = new MapPubSub(); DB db = initMongoDB(); collection = db.getCollection("customer"); collection.drop(); BasicDBObject basicDBObject = new BasicDBObject(); basicDBObject.put("_id", "testid"); basicDBObject.put("testField", "pippo"); collection.insert(basicDBObject); action.addInvoker( new MongoDBMethodInvoker( db, pubSub, new IdGenerator() { @Override public String generateCollectionID(String randomSeed) { return "fixed"; } })); mockSession = new MockSession(); session = new DDPSession(mockSession); pubSub.sub( new Sub() { { setName("customer"); } }, session); }
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(); DB db = client.getDB("course"); DBCollection lines = db.getCollection("dotNotationTest"); lines.drop(); Random rand = new Random(); for (int i = 0; i < 10; i++) { lines.insert( new BasicDBObject("_id", i) .append( "start", new BasicDBObject("x", rand.nextInt(90) + 10).append("y", rand.nextInt(90) + 10)) .append( "end", new BasicDBObject("x", rand.nextInt(90) + 10) .append("y", rand.nextInt(90) + 10))); } QueryBuilder builder = QueryBuilder.start("start.x").greaterThan(50); DBCursor cursor = lines.find(builder.get(), new BasicDBObject("start.y", true).append("_id", false)); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
@Override public String ActualizarJson(String nombreDB, String json, int clienteId) throws UnknownHostException { // TODO Auto-generated method stub if (!ExisteCliente(nombreDB, clienteId)) { // System.out.println("********************\n"); // System.out.println("No existe el cliente, no se puede actualizar"); // System.out.println("********************\n"); return "No existe el cliente, no se puede actualizar"; } MongoClient mongoClient = new MongoClient("localhost", 27017); DB base = mongoClient.getDB(nombreDB); DBCollection collection = base.getCollection("Json"); BasicDBObject document = new BasicDBObject(); DBObject object = (DBObject) JSON.parse(json); document.put("id", clienteId); document.put("json", object); BasicDBObject query = new BasicDBObject().append("id", clienteId); collection.findAndModify(query, document); return "Cliente actualizado"; }
public static void main(String[] args) throws Exception { MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("mydb"); DBCollection coll = db.getCollection("collection"); lanciaTest(coll); }
@Override public String Json(String nombreDB, int clienteId) throws UnknownHostException, JSONException { // TODO Auto-generated method stub MongoClient mongoClient = new MongoClient("localhost", 27017); DB base = mongoClient.getDB(nombreDB); DBCollection collection = base.getCollection("Json"); BasicDBObject query = new BasicDBObject(); query.put("id", clienteId); DBCursor cursor = collection.find(query); if (cursor.size() == 0) { // System.out.println("********************\n"); // System.out.println("No existe el cliente, no se puede ingresar json"); // System.out.println("********************\n"); return "No existe el cliente, no se puede ingresar json"; } // Existe el cliente DBObject objeto = (DBObject) cursor.next(); DBObject json = (DBObject) objeto.get("json"); // DBObject j = JSON.parse(json.toString()); JSONObject aj = new JSONObject(json.toString()); return aj.toString(); }
private String selectBooks( String schema, String collection, String title, String author, String isbn) throws UnknownHostException { System.out.println(schema); System.out.println(collection); System.out.println(title); System.out.println(author); List<String> l = new ArrayList<String>(); MongoDBConnectionManager mgr = MongoDBConnectionManager.getInstance(); Mongo mongo = mgr.getMongo(); DB db = mongo.getDB(schema); try { DBCollection c = db.getCollection(collection); BasicDBObject titleQuery = new BasicDBObject(); titleQuery.put("title", new BasicDBObject("$regex", title)); BasicDBObject authorQuery = new BasicDBObject(); authorQuery.put("author", new BasicDBObject("$regex", author)); BasicDBList or = new BasicDBList(); or.add(titleQuery); or.add(titleQuery); DBObject query = new BasicDBObject("$and", or); DBCursor cursor = c.find(titleQuery); while (cursor.hasNext()) l.add(cursor.next().toString()); } catch (Exception e) { System.out.println(e.getMessage()); } System.out.println(l); if (l.size() > 0) return l.toString(); else return null; }