"Select cola, colb, colc, cold from Table web-services where cola='1000' and colb='DAO' and group by colc"
I need a simple example in Mongodb 3.x API to have Filters with Projections for the values passed to keys in the SQL query above.
Hi Karthik,
I would recommend to first try out MongoDB Aggregation Pipeline via mongo shell before attempting to apply it using a driver.
The equivalent of the above SQL in mongo shell
would be:
db.collectionName.aggregate([
{$match:{cola:"1000", colb:"DAO"}},
{$group:{"_id":"$colc", cola:{$first:"$cola"}, colb:{$first:"$colb"}, cold:{$first:"$cold"}}},
{$project:{_id:0, cola:"$cola", colb:"$colb", colc:"$_id", cold:"$cold"}}
]);
Note that above I’m utilising $first group accumulator above for cola
, colb
and cold
. Please see Group Accumulator Operators for other aggregation operations.
Using MongoDB Java driver, the equivalent aggregation pipeline above is as below:
MongoDatabase db = mongoClient.getDatabase("dbName");
Document match = Document.parse("{$match:{cola:'1000', colb:'DAO'}}");
Document group = Document.parse("{$group:{'_id':'$colc', cola:{$first:'$cola'}, colb:{$first:'$colb'}, cold:{$first:'$cold'}}}");
Document project = Document.parse("{$project:{cola:'$cola', colb:'$colb', colc:'$_id', cold:'$cold', _id:0}}");
List<Document> pipeline = asList(match, group, project);
AggregateIterable<Document> iterable = db.getCollection("collectionName").aggregate(pipeline);
See also MongoDB Java driver: Aggregation Framework tutorials
Regards,
Wan.