Java Mongodb 3.x ~ Specific document key's with value and

28 views
Skip to first unread message

N.S.KARTHIK

unread,
Jul 24, 2017, 12:51:44 AM7/24/17
to mongodb-user
Spec : Jdk 1.7,Mongodb 3.0.12,Win-10

  I have gone thru all of the Mongo's docs :  http://mongodb.github.io/mongo-java-driver/3.4/driver/tutorials/

  I have done some samples suggested by Professionals on Filter & projections.

  Question  I am still not able to achieve the following equivalence of an SQL query in MongoDB's NO-SQL

     "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.



with regards
Karthik

Wan Bachtiar

unread,
Jul 31, 2017, 4:05:15 AM7/31/17
to mongodb-user

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.

Reply all
Reply to author
Forward
0 new messages