List of usage examples for com.mongodb DBCollection aggregate
public Cursor aggregate(final List<? extends DBObject> pipeline, final AggregationOptions options)
From source file:org.kiaan.Main.java
private static void getBuy() { try {// w ww . jav a 2 s. c o m MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("kiaan"); DBCollection coll = db.getCollection("buy"); //aggregate DBObject unwind = new BasicDBObject("$unwind", "$items"); //$group DBObject group_id = new BasicDBObject("_id", "$_id"); group_id.put("num", "$num"); group_id.put("person_id", "$person_id"); group_id.put("discount", "$discount"); group_id.put("increase", "$increase"); //$group -> $multiply BasicDBList args = new BasicDBList(); args.add("$items.value"); args.add("$items.price"); DBObject multiply = new BasicDBObject("$multiply", args); //$group -> $sum // DBObject group_sum = new BasicDBObject("$sum", multiply); DBObject group_field = new BasicDBObject(); group_field.put("_id", group_id); group_field.put("total", new BasicDBObject("$sum", multiply)); DBObject group = new BasicDBObject("$group", group_field); //$project DBObject project_field = new BasicDBObject("_id", "$_id._id"); project_field.put("person_id", "$_id.person_id"); project_field.put("num", "$_id.num"); BasicDBList arr = new BasicDBList(); arr.add("$total"); arr.add("$_id.discount"); arr.add("$_id.increase"); DBObject field_add = new BasicDBObject("$add", arr); project_field.put("sum", field_add); DBObject project = new BasicDBObject("$project", project_field); DBObject sort = new BasicDBObject("$sort", new BasicDBObject("_id", 1)); List<DBObject> pipeline = Arrays.asList(unwind, group, project, sort); // AggregationOutput output = coll.aggregate(pipeline); // for (DBObject result : output.results()) { // System.out.println(result); // } AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); BasicDBObject dbo = new BasicDBObject(); BasicDBList dbl = new BasicDBList(); Cursor cursor = coll.aggregate(pipeline, aggregationOptions); // DBCollection person_col = db.getCollection("persons"); // BasicDBObject query = new BasicDBObject("items.personId",1); BasicDBObject fields = new BasicDBObject("items.$", 1).append("_id", false); // BasicDBList l_per = (BasicDBList) person_col.findOne(query, fields).get("items"); // BasicDBObject[] lightArr = l_per.toArray(new BasicDBObject[0]); // System.out.println(lightArr[0].get("_id")); // System.out.println(lightArr[0].get("first_name")); BasicDBList result = new BasicDBList(); while (cursor.hasNext()) { dbo = (BasicDBObject) cursor.next(); // System.out.println(dbo.toString()); DBObject query = new BasicDBObject("items._id", (ObjectId) dbo.get("person_id")); BasicDBList lst_person = (BasicDBList) person_col.findOne(query, fields).get("items"); BasicDBObject[] lightArr = lst_person.toArray(new BasicDBObject[0]); // System.out.println(lightArr[0].get("first_name")); Date date = ((ObjectId) lightArr[0].get("_id")).getDate(); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); persianCalendar persianCalendar = new persianCalendar(calendar); dbo.put("date", persianCalendar.getNumericDateFormatWithTime()); dbo.put("personId", lightArr[0].get("personId").toString()); dbo.put("first_name", lightArr[0].get("first_name").toString()); dbo.put("last_name", lightArr[0].get("last_name").toString()); dbo.removeField("person_id"); result.add(dbo); // System.out.println(dbo.get("num")); } System.out.println(result.toString()); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:org.teiid.translator.mongodb.MongoDBDirectQueryExecution.java
License:Open Source License
@Override public void execute() throws TranslatorException { StringBuilder buffer = new StringBuilder(); SQLStringVisitor.parseNativeQueryParts(query, arguments, buffer, new SQLStringVisitor.Substitutor() { @Override//from w w w. jav a2s . c om public void substitute(Argument arg, StringBuilder builder, int index) { Literal argumentValue = arg.getArgumentValue(); builder.append(argumentValue.getValue()); } }); StringTokenizer st = new StringTokenizer(buffer.toString(), ";"); //$NON-NLS-1$ String collectionName = st.nextToken(); boolean shellOperation = collectionName.equalsIgnoreCase("$ShellCmd"); //$NON-NLS-1$ String shellOperationName = null; if (shellOperation) { collectionName = st.nextToken(); shellOperationName = st.nextToken(); } DBCollection collection = this.mongoDB.getCollection(collectionName); if (collection == null) { throw new TranslatorException(MongoDBPlugin.Event.TEIID18020, MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18020, collectionName)); } if (shellOperation) { ArrayList<Object> operations = new ArrayList<Object>(); while (st.hasMoreTokens()) { String token = st.nextToken(); if (token.startsWith("{")) { //$NON-NLS-1$ operations.add(JSON.parse(token)); } else { operations.add(token); } } try { ReflectionHelper helper = new ReflectionHelper(DBCollection.class); Method method = helper.findBestMethodOnTarget(shellOperationName, operations.toArray(new Object[operations.size()])); Object result = method.invoke(collection, operations.toArray(new Object[operations.size()])); if (result instanceof Cursor) { this.results = (Cursor) result; } else if (result instanceof WriteResult) { WriteResult wr = (WriteResult) result; if (wr.getError() != null) { throw new TranslatorException(wr.getError()); } } } catch (NoSuchMethodException e) { throw new TranslatorException(MongoDBPlugin.Event.TEIID18034, e, MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18034, buffer.toString())); } catch (SecurityException e) { throw new TranslatorException(MongoDBPlugin.Event.TEIID18034, e, MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18034, buffer.toString())); } catch (IllegalAccessException e) { throw new TranslatorException(MongoDBPlugin.Event.TEIID18034, e, MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18034, buffer.toString())); } catch (IllegalArgumentException e) { throw new TranslatorException(MongoDBPlugin.Event.TEIID18034, e, MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18034, buffer.toString())); } catch (InvocationTargetException e) { throw new TranslatorException(MongoDBPlugin.Event.TEIID18034, e.getTargetException(), MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18034, buffer.toString())); } } else { ArrayList<DBObject> operations = new ArrayList<DBObject>(); while (st.hasMoreTokens()) { String token = st.nextToken(); operations.add((DBObject) JSON.parse(token)); } if (operations.isEmpty()) { throw new TranslatorException(MongoDBPlugin.Event.TEIID18021, MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18021, collectionName)); } this.results = collection.aggregate(operations, this.executionFactory.getOptions(this.executionContext.getBatchSize())); } }
From source file:org.teiid.translator.mongodb.MongoDBQueryExecution.java
License:Open Source License
@Override public void execute() throws TranslatorException { this.visitor = new MongoDBSelectVisitor(this.executionFactory, this.metadata); this.visitor.visitNode(this.command); if (!this.visitor.exceptions.isEmpty()) { throw this.visitor.exceptions.get(0); }//www . j a va 2s.co m LogManager.logInfo(LogConstants.CTX_CONNECTOR, this.command); DBCollection collection = this.mongoDB.getCollection(this.visitor.mongoDoc.getTargetTable().getName()); if (collection != null) { // TODO: check to see how to pass the hint ArrayList<DBObject> ops = new ArrayList<DBObject>(); for (ProcessingNode ref : this.visitor.mergePlanner.getNodes()) { buildAggregate(ops, ref.getInstruction()); } if (this.visitor.project.isEmpty()) { throw new TranslatorException(MongoDBPlugin.Event.TEIID18025, MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18025)); } assert visitor.selectColumns.size() == visitor.selectColumnReferences.size(); if (this.visitor.projectBeforeMatch) { buildAggregate(ops, "$project", this.visitor.project); //$NON-NLS-1$ } buildAggregate(ops, "$match", this.visitor.match); //$NON-NLS-1$ buildAggregate(ops, "$group", this.visitor.group); //$NON-NLS-1$ buildAggregate(ops, "$match", this.visitor.having); //$NON-NLS-1$ if (!this.visitor.projectBeforeMatch) { buildAggregate(ops, "$project", this.visitor.project); //$NON-NLS-1$ } buildAggregate(ops, "$sort", this.visitor.sort); //$NON-NLS-1$ buildAggregate(ops, "$skip", this.visitor.skip); //$NON-NLS-1$ buildAggregate(ops, "$limit", this.visitor.limit); //$NON-NLS-1$ try { this.results = collection.aggregate(ops, this.executionFactory.getOptions(this.executionContext.getBatchSize())); } catch (MongoException e) { throw new TranslatorException(e); } } }
From source file:org.teiid.translator.mongodb.MongoDBUpdateExecution.java
License:Open Source License
private void executeInternal() throws TranslatorException { DBCollection collection = getCollection(this.visitor.mongoDoc.getTargetTable()); MongoDocument mongoDoc = this.visitor.mongoDoc; AggregationOptions options = this.executionFactory.getOptions(this.executionContext.getBatchSize()); List<WriteResult> executionResults = new ArrayList<WriteResult>(); if (this.command instanceof Insert) { // get pull key based documents to embed LinkedHashMap<String, DBObject> embeddedDocuments = fetchEmbeddedDocuments(); // check if this document need to be embedded in any other document if (mongoDoc.isMerged()) { DBObject match = getInsertMatch(mongoDoc, this.visitor.columnValues); BasicDBObject insert = this.visitor.getInsert(embeddedDocuments); if (mongoDoc.getMergeKey().getAssociation() == Association.MANY) { removeParentKey(mongoDoc, insert); BasicDBObject insertDoc = new BasicDBObject(mongoDoc.getQualifiedName(true), insert); LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$match\": {" + match + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$push\": {" + insertDoc + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ executionResults.add(collection.update(match, new BasicDBObject("$push", insertDoc), false, //$NON-NLS-1$ true, WriteConcern.ACKNOWLEDGED)); } else { insert.remove("_id"); //$NON-NLS-1$ BasicDBObject insertDoc = new BasicDBObject(mongoDoc.getQualifiedName(true), insert); LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$match\": {" + match + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$set\": {" + insertDoc + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ executionResults.add(collection.update(match, new BasicDBObject("$set", insertDoc), false, true, //$NON-NLS-1$ WriteConcern.ACKNOWLEDGED)); }/*from w w w. jav a 2s. c o m*/ } else { for (String docName : embeddedDocuments.keySet()) { DBObject embeddedDoc = embeddedDocuments.get(docName); embeddedDoc.removeField("_id"); //$NON-NLS-1$ } // gets its own collection BasicDBObject in = this.visitor.getInsert(embeddedDocuments); LogManager.logDetail(LogConstants.CTX_CONNECTOR, "{\"insert\": {" + in + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ executionResults.add(collection.insert(in, WriteConcern.ACKNOWLEDGED)); } } else if (this.command instanceof Update) { // get pull key based documents to embed LinkedHashMap<String, DBObject> embeddedDocuments = fetchEmbeddedDocuments(); DBObject match = new BasicDBObject(); if (this.visitor.match != null) { match = this.visitor.match; } if (mongoDoc.isMerged()) { // multi items in array update not available, http://jira.mongodb.org/browse/SERVER-1243 // this work-around for above issue List<String> parentKeyNames = parentKeyNames(mongoDoc); DBObject documentMatch = new BasicDBObject("$match", match); //$NON-NLS-1$ DBObject projection = new BasicDBObject("$project", buildProjectForUpdate(mongoDoc)); //$NON-NLS-1$ Cursor output = collection.aggregate(Arrays.asList(documentMatch, projection), options); while (output.hasNext()) { BasicDBObject row = (BasicDBObject) output.next(); buildUpdate(mongoDoc, collection, row, parentKeyNames, 0, null, executionResults, new UpdateOperationImpl()); } } else { for (String docName : embeddedDocuments.keySet()) { DBObject embeddedDoc = embeddedDocuments.get(docName); embeddedDoc.removeField("_id"); //$NON-NLS-1$ } BasicDBObject u = this.visitor.getUpdate(embeddedDocuments); LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$match\": {" + match + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "update - {\"$set\": {" + u + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ executionResults.add(collection.update(match, new BasicDBObject("$set", u), false, true, //$NON-NLS-1$ WriteConcern.ACKNOWLEDGED)); } // if the update is for the "embeddable" table, then since it is copied to other tables // those references need to be updated. I know this is not atomic operation, but not sure // how else to handle it. if (mongoDoc.isEmbeddable()) { updateReferenceTables(collection, mongoDoc, match, options); } } else { // Delete DBObject match = new BasicDBObject(); if (this.visitor.match != null) { match = this.visitor.match; } if (mongoDoc.isEmbeddable()) { DBObject m = new BasicDBObject("$match", match); //$NON-NLS-1$ Cursor output = collection.aggregate(Arrays.asList(m), options); while (output.hasNext()) { DBObject row = output.next(); if (row != null) { for (MergeDetails ref : mongoDoc.getEmbeddedIntoReferences()) { DBCollection parent = getCollection(ref.getParentTable()); DBObject parentMatch = buildParentMatch(row, ref); DBObject refMatch = new BasicDBObject("$match", parentMatch); //$NON-NLS-1$ Cursor referenceOutput = parent.aggregate(Arrays.asList(refMatch), options); if (referenceOutput.hasNext()) { throw new TranslatorException(MongoDBPlugin.Util.gs(MongoDBPlugin.Event.TEIID18010, this.visitor.mongoDoc.getTargetTable().getName(), ref.getParentTable())); } } } } } if (mongoDoc.isMerged()) { List<String> parentKeyNames = parentKeyNames(mongoDoc); DBObject documentMatch = new BasicDBObject("$match", match); //$NON-NLS-1$ DBObject projection = new BasicDBObject("$project", buildProjectForUpdate(mongoDoc)); //$NON-NLS-1$ Cursor output = collection.aggregate(Arrays.asList(documentMatch, projection), options); while (output.hasNext()) { BasicDBObject row = (BasicDBObject) output.next(); buildUpdate(mongoDoc, collection, row, parentKeyNames, 0, null, executionResults, new DeleteOperationImpl(match)); } } else { LogManager.logDetail(LogConstants.CTX_CONNECTOR, "remove - {\"$match\": {" + match + "}}"); //$NON-NLS-1$ //$NON-NLS-2$ executionResults.add(collection.remove(match, WriteConcern.ACKNOWLEDGED)); } } if (!executionResults.isEmpty()) { if (this.command instanceof Insert) { if (this.executionContext.getCommandContext().isReturnAutoGeneratedKeys()) { addAutoGeneretedKeys(executionResults.get(0)); } } int updated = 0; for (WriteResult result : executionResults) { updated += result.getN(); } this.results = new int[1]; this.results[0] = updated; } }
From source file:org.teiid.translator.mongodb.MongoDBUpdateExecution.java
License:Open Source License
private void updateReferenceTables(DBCollection collection, MongoDocument mongoDoc, DBObject match, AggregationOptions options) throws TranslatorException { DBObject m = new BasicDBObject("$match", match); //$NON-NLS-1$ Cursor output = collection.aggregate(Arrays.asList(m), options); while (output.hasNext()) { DBObject row = output.next();/*from w ww .jav a2 s . co m*/ if (row != null) { for (MergeDetails ref : mongoDoc.getEmbeddedIntoReferences()) { DBCollection parent = getCollection(ref.getParentTable()); //DBObject parentmatch = new BasicDBObject(ref.getReferenceName()+".$id", row.get("_id")); //$NON-NLS-1$ //$NON-NLS-2$ DBObject parentmatch = buildParentMatch(row, ref); row.removeField("_id"); //$NON-NLS-1$ parent.update(parentmatch, new BasicDBObject("$set", new BasicDBObject(ref.getName(), row)), //$NON-NLS-1$ false, true, WriteConcern.ACKNOWLEDGED); // see if there are nested references Table parentTable = this.metadata.getTable(mongoDoc.getTable().getParent().getName(), ref.getParentTable()); MongoDocument parentMongoDocument = new MongoDocument(parentTable, this.metadata); if (parentMongoDocument.isEmbeddable()) { updateReferenceTables(parent, parentMongoDocument, parentmatch, options); } } } } }
From source file:pt.tiago.mongodbteste.MongoDB.java
private void queries() { DBCollection coll = db.getCollection("Purchase"); //find the sum group by category DBObject group = new BasicDBObject("$group", new BasicDBObject("_id", "$categoryID").append("total", new BasicDBObject("$sum", "$price"))); DBObject sort = new BasicDBObject("$sort", new BasicDBObject("price", 1)); AggregationOutput output = coll.aggregate(group, sort); for (DBObject result : output.results()) { System.out.println(result); }//from ww w.j a v a 2 s. co m System.out.println("////////////////////////////////"); //find the year of date //SELECT DISTINCT(YEAR(DateOfPurchase)) AS ano FROM Purchase // $group : {_id : { year : {$year : "$birth_date"}}, total : {$sum : 1} System.out.println("SELECT DISTINCT(YEAR(DateOfPurchase)) AS ano FROM Purchase"); DBCollection collection2 = db.getCollection("Purchase"); group = new BasicDBObject("$group", new BasicDBObject("_id", new BasicDBObject("year", new BasicDBObject("$year", "$dateOfPurchase"))) .append("total", new BasicDBObject("$sum", 1))); output = collection2.aggregate(group); BasicDBObject basicObj; for (DBObject result : output.results()) { basicObj = (BasicDBObject) result; basicObj = (BasicDBObject) basicObj.get("_id"); System.out.println(basicObj.get("year")); ; } System.out.println("////////////////////////////////"); //find the sum with year and categoryID // SELECT SUM(Price) AS Sumatorio FROM Purchase WHERE CategoryID = ? AND Year(DateOfPurchase) = ? System.out.println( "SELECT SUM(Price) AS Sumatorio FROM Purchase WHERE CategoryID = ? AND Year(DateOfPurchase) = ?"); int year = 2014; Calendar cal = Calendar.getInstance(); cal.set(year, 0, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(year, 11, 31); BasicDBObject match = new BasicDBObject("$match", new BasicDBObject("categoryID", new ObjectId("548089fc46e68338719aa1f8"))); match.put("$match", new BasicDBObject("dateOfPurchase", new BasicDBObject("$gte", cal.getTime()).append("$lt", cal2.getTime()))); group = new BasicDBObject("$group", new BasicDBObject("_id", null).append("total", new BasicDBObject("$sum", "$price"))); output = coll.aggregate(match, group); for (DBObject result : output.results()) { basicObj = (BasicDBObject) result; System.out.println(basicObj.getDouble("total")); } System.out.println("////////////////////////////////"); System.out.println("SELECT SUM(Price) , MONTH(DateOfPurchase)" + " FROM Purchase WHERE PersonID = ? AND CategoryID = ? " + "AND Price <= ? GROUP BY MONTH(DateOfPurchase)"); coll = db.getCollection("Purchase"); BasicDBObject cateObj = new BasicDBObject("categoryID", new ObjectId("548089fc46e68338719aa1f8")); BasicDBObject personObj = new BasicDBObject("personID", new ObjectId("548079fa46e68338719aa1f6")); BasicDBList and = new BasicDBList(); and.add(cateObj); and.add(personObj); DBObject andCriteria = new BasicDBObject("$and", and); DBObject matchCriteria = new BasicDBObject("$match", andCriteria); group = new BasicDBObject("$group", new BasicDBObject("_id", null).append("total", new BasicDBObject("$sum", "$price"))); group.put("$group", new BasicDBObject("_id", new BasicDBObject("month", new BasicDBObject("$month", "$dateOfPurchase"))) .append("total", new BasicDBObject("$sum", "$price"))); output = coll.aggregate(matchCriteria, group); for (DBObject result : output.results()) { basicObj = (BasicDBObject) result; System.out.println(basicObj.toString()); } System.out.println("////////////////////////////////"); System.out.println("SELECT SUM(Price) , PersonID FROM Purchase WHERE " + "YEAR(DateOfPurchase) = ? AND Price <= ? GROUP BY PersonID"); coll = db.getCollection("Purchase"); year = 2014; cal = Calendar.getInstance(); cal.set(year, 0, 0); cal2 = Calendar.getInstance(); cal2.set(year, 11, 31); BasicDBObject priceObj = new BasicDBObject("price", new BasicDBObject("$lte", 2000)); BasicDBObject dateObj = new BasicDBObject("dateOfPurchase", new BasicDBObject("$gte", cal.getTime()).append("$lt", cal2.getTime())); and = new BasicDBList(); and.add(priceObj); and.add(dateObj); andCriteria = new BasicDBObject("$and", and); matchCriteria = new BasicDBObject("$match", andCriteria); group = new BasicDBObject("$group", new BasicDBObject("_id", "$personID").append("total", new BasicDBObject("$sum", "$price"))); output = coll.aggregate(matchCriteria, group); for (DBObject result : output.results()) { basicObj = (BasicDBObject) result; System.out.println(basicObj.toString()); } }
From source file:yelpapp.HW3.java
public List getReviewBusiness(Date reviewfrom, Date Reviewto, String Stars_cond, String Stars_value, String votes_cond, String votes_value) { MongoClient client;//from w w w. j a va2 s . c om client = new MongoClient(new MongoClientURI("mongodb://localhost:27017")); DB db1 = new MongoClient("localhost", 27017).getDB("YelpApplication"); DBCollection dbcollection = db1.getCollection("YelpReview"); ArrayList businessiidList = null; String searchForComboBox = "and"; BasicDBObject votescountcondDBOB = null; BasicDBObject votescountcond1 = null; BasicDBObject averagestarscondDBOB = null; BasicDBObject averagestarscond1 = null; BasicDBObject begincondDBOB = null; BasicDBObject rdatecondDBOB = null; if (reviewfrom != null && Reviewto != null && (!Stars_value.equalsIgnoreCase("0") && !votes_value.equalsIgnoreCase("0"))) { DateFormat df = new SimpleDateFormat("dd-MMM-yyyy"); String date_string_reviewfrom = df.format(reviewfrom); String date_string_reviewto = df.format(Reviewto); String rdatecond = "$gt"; begincondDBOB = new BasicDBObject("$gt", reviewfrom).append("$lt", Reviewto);//" ISODate("+datestr+")" rdatecondDBOB = new BasicDBObject("date", begincondDBOB); System.out.println("rdatecondDBOB" + rdatecondDBOB); if (!votes_value.equalsIgnoreCase("0")) { String reviewcond = condstr(votes_cond); votescountcondDBOB = new BasicDBObject(reviewcond, Double.parseDouble(votes_value)); votescountcond1 = new BasicDBObject("totalVotes", votescountcondDBOB); } if (!Stars_value.equalsIgnoreCase("0")) { String starscond = condstr(Stars_cond); averagestarscondDBOB = new BasicDBObject(starscond, Integer.parseInt(Stars_value)); averagestarscond1 = new BasicDBObject("stars", averagestarscondDBOB); } String datestr = "2014-12-09T00:00:00Z"; System.out.println("start" + "new ISODate(" + datestr + ")"); String option = "$and"; BasicDBObject proj1 = new BasicDBObject(); List<BasicDBObject> asList = new ArrayList<BasicDBObject>(); // asList.add(rdatecondDBOB);//reviewcountcond1,averagestarscond1,friendsDOB if (null != averagestarscond1) asList.add(averagestarscond1); if (null != rdatecondDBOB) asList.add(rdatecondDBOB); if (null != votescountcond1) asList.add(votescountcond1); DBObject optioncond = new BasicDBObject(option, asList); /* db.YelpUser.aggregate([ { $match: { $and: [ {date: {$gt: 3,$lt :5}}, {stars: {$gt: 3}}, {$votes.useful: {$gt:2}}, ] } } ])*/ System.out.println("optioncond =" + optioncond); System.out.println("option" + option); DBObject match = new BasicDBObject("$match", optioncond); System.out.println("match =" + match); DBObject project = new BasicDBObject("$project", new BasicDBObject("business_id", 1).append("_id", 0)); System.out.println(match); AggregationOutput output = dbcollection.aggregate(match, project); System.out.println("output" + output); // query = match.toString(); businessiidList = new ArrayList<String>(); for (DBObject result : output.results()) { System.out.println("reviews" + result); businessiidList.add(result.get("business_id")); //System.out.println(businessiidList); } } System.out.println("Done executing review"); return businessiidList; }